Solved

jQuery does not trigger on HTML loaded via AJAX call

Posted on 2014-02-08
7
699 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
how to debug htl and js pages 8 39
jQuery Toggle & Anchor Links 5 43
Bootstrap date picker V2 date restriction 6 38
Need HTML output in powershell line by line 3 30
This article describes how to create custom column layout styles for Bootstrap. The article uses 5 columns to illustrate the concept, but the principle can be extended to any number of columns.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
In this tutorial viewers will learn how to embed an audio file in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: : The declaration should display (CODE) HTML5 is supported by the most recent versions of all major browsers…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

828 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