Solved

jQuery does not trigger on HTML loaded via AJAX call

Posted on 2014-02-08
7
693 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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
In this tutorial viewers will learn how add a scalable full-width header using CSS3. Create a new HTML document with an internal stylesheet. Set a tiled background.:  Create a new div and name it Header. Position it with position:absolute at the top…
In this Micro Tutorial viewers will learn how to create navigation buttons that change on rollover, using CSS (Continuation of the CSS Image Sprite tutorial) Create a parent ID for all the list items       - Specify position: absolute and display: block…

743 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

12 Experts available now in Live!

Get 1:1 Help Now