Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery elements ignoring click() code if added to DOM after pageload

Tags:

jquery

dom

So I have some code and I add an element to the DOM after pageload (the second link in the below example) however this newly added element ignores all functions defined for it. So for the example below I want all links in div's with the test class to show an alert. Works fine for the link hard coded but the one added afterwards ignores it.

<html>
    <head>
        <title>SO Test</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    </head>
    <body>
        <div class="test">
            <a href="#" title="Test">Test Link</a>
        </div>
        <script type="text/javascript">
        <!--    
            $(document).ready(function() {

                $("div.test a").click(function() {
                    alert("click");
                    return false;
                });

                $(document.createElement("a")).attr("href","#").text("Test Link 2").appendTo("div.test");

            });
        -->
        </script>
    </body>
</html>

EDIT: Is the only solution to abstract it away with a jQuery plugin?

like image 280
Andrew G. Johnson Avatar asked Oct 15 '09 19:10

Andrew G. Johnson


People also ask

Why click function is not working in jQuery?

The fix is easy enough, simply bind the OnClick event to the parent of the elements you want to be able to click on. That way, if the element you want to click on is removed and re-appended, the handler will still be there listening as the parent was never removed.

How do you execute a function right after page loads without calling a method function?

First Simple Way. You also know that in HTML <body> tag holds the actual content that is used to display to the users. Using the onload with HTML <body> tag, you can execute the javascript function after the whole page is loaded. The onload event occurs whenever the element has finished loading.

How can we call a method after page load in jQuery?

If you want an event to work on your page, you should call it inside the $(document). ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.

How do you bind a click event to dynamically created elements?

You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.


1 Answers

Your issue is that click() binds an event listener to each element in the current matched set. It's not magic, and it won't retroactively apply the event listener to new content you add to the DOM. Your options are:

  1. Use the live events functionality in jQuery, as others have mentioned.
  2. Do something similar yourself, by binding a click handler to some common ancestor of the elements in which you're interested, and then testing the target of each click you see to determine whether you care about it. For example:
    $(function(){
      $("div.test").click(function(e){
        if( $(e.target).is("a") ) {
          alert("click");
          return false;
        });
      });
    });
  3. In the code that adds the new elements to the DOM, also bind event handlers to them. For example:
    $(document.createElement("a"))
      .attr("href","#")
      .text("Test Link 2")
      .click(function(){ alert("click"); })
      .appendTo("div.test");
like image 146
Sixten Otto Avatar answered Oct 06 '22 18:10

Sixten Otto