Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

jQuery does not trigger on HTML loaded via AJAX call

Posted on 2014-02-08
7
Medium Priority
?
716 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
7 Comments
 
LVL 58

Accepted Solution

by:
Gary earned 2000 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

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

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Is your Office 365 signature not working the way you want it to? Are signature updates taking up too much of your time? Let's run through the most common problems that an IT administrator can encounter when dealing with Office 365 email signatures.
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

618 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