Solved

jQuery does not trigger on HTML loaded via AJAX call

Posted on 2014-02-08
7
695 Views
Last Modified: 2014-02-08
I have a page which declares some jQuery code and I cannot get it to trigger on HTML which has been loaded using AJAX.

I have created the following simple code to illustrate the problem. It is a very simple page containing a link with a class called "link". There is also a div which will contain an external HTML file which also contains another link with the same "link" class applied to it. The jQuery triggers on the "link" class and pops up an alert.

It works when you click on "Click parent link" but not when you click on "Click loaded link" even though both links have the same class.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
</head>

<body>

    <script type="text/javascript">
    //<![CDATA[
    $(document).ready(function(){

        $('#internaldiv').load('link.htm');

        $(".link").click(function(){		
            alert("Link clicked");
            return false;
        });

    });
    //]]>
    </script>
    
    <a class="link" href="#">Click parent link</a>
    
    <div id="internaldiv">
    
    </div>

</body>
</html>

Open in new window


Here is the external link.htm file:

<a class="link" href="#">Click loaded link</a>

Open in new window


In the example given, the div loads on document ready, however it could equally load on some other event say clicking on a button or link.
0
Comment
Question by:mike99c
  • 3
  • 3
7 Comments
 
LVL 58

Accepted Solution

by:
Gary earned 500 total points
ID: 39844622
http://api.jquery.com/on/

        $(document).on("click",".link",function(){		
            alert("Link clicked");
            return false;
        });

Open in new window

0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 39844669
The ajax loaded page does not yet exist in the DOM when the parent page is "ready". By then the click event listener has already been assigned to the only existing class="link" on the page.

Consider this example where the click event listeners are not assigned until there are more than one class="link" elements present.
<script type="text/javascript">
    //<![CDATA[
    $(document).ready(function(){

        $('#internaldiv').load('link.htm');
		var test = setInterval(function(){
			if ($('.link').length > 1) {
				clearInterval(test);
				$(".link").click(function(){							
            		alert("#" + $(this).index() + " Link clicked");
            		return false;
				});
        	}
		}, 300);

    });
    //]]>
    </script>

Open in new window

0
 
LVL 58

Expert Comment

by:Gary
ID: 39844685
That is an example of how not to use jquery.
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 38

Expert Comment

by:Tom Beck
ID: 39844690
Okay Gary, you have the better solution. That's why you are the Ace.
0
 
LVL 58

Expert Comment

by:Gary
ID: 39844697
Nothing to do with the better solution, it is the solution. That is what .on is for
Your way is looping javascript until it can find two elements with the class, and then will never run again to capture any new links.
On top of that the click event won't even exist for the first link until there are two links.
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 39844704
I totally understand my mistake now. Thanks for elaborating. I've still got some learning to do. I won't give up my day job just yet.
0
 

Author Closing Comment

by:mike99c
ID: 39844743
Thanks Cathal, that did the trick. It's 01:14 in the morning here in London and I can now get some sleep.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
In this tutorial viewers will learn how to position overlapping items using z-index in CSS. They will also learn the restrictions on the z-index property.  Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Red.…
In this tutorial viewers will learn how to embed Flash content in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <object> tag to embed Flash content.: To specify that the object is Flash content, d…

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now