Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click event, after appending content

Tags:

jquery

Wondering why the example below doesn't work?

<a id="load_list" href="#">Load the list</a>

<ul></ul>

<script type="text/javascript">
$(document).ready(function() {
    $('#load_list').click(function() {
        $('ul').append('<li><a href="#">Click here</a></li>');
        return false;
    });
    $('ul li a').click(function() {
        alert('Thank you for clicking');
        return false;
    });
});
</script>
like image 995
Pav Avatar asked Apr 08 '11 01:04

Pav


4 Answers

Because the elements that you are appending do not exist when you define the the click handler, they are created dynamically. To fix this you can use the delegate() method from jQuery.

$('ul').delegate('a','click',function() {
    // your code here ...
});

Online example: http://jsfiddle.net/J5QJ9/

like image 82
amosrivera Avatar answered Dec 25 '22 16:12

amosrivera


From jQuery 1.7 you can use the .on() handler to bind the newly created element ot the 'click' event:

<script type="text/javascript">
$(document).ready(function() {
    $('#load_list').click(function() {
        $('ul').append('<li><a href="#">Click here</a></li>').on('click', 'ul li a', function () {
            alert('thank you for clicking');
        });
    });
</script>

(this is with the original example).

like image 37
Carlos Tapia Avatar answered Dec 25 '22 18:12

Carlos Tapia


$(document).on('click','ul li a', function(){
      // Content Code
});
like image 22
Matsteel Avatar answered Dec 25 '22 16:12

Matsteel


.live is deprecated as of 1.7. Try this (jquery 2.1.4):

Html:

<a id="load_list" href="#">Load the list</a>

<ul></ul>

JQuery:

$(document).ready(function() {

 $('#load_list').click(function() {
   $('ul').html("");    

   $("<li/>", {
        "class" : "someClass",
        text: "Click here",
        click: function() {
          alert($(this).text());
        }
      }).appendTo('ul');
  });
});

or something like this (but I didn't find how to attach click to the anchor):

$(document).ready(function() {
 $('#load_list').click(function() {
   $('ul').html("");

   $('<li><a href="#">Click here</a></li>').on({
      click: function() {
        alert("hoi");
      }
    }).appendTo("ul");
 });
});
like image 37
juFo Avatar answered Dec 25 '22 18:12

juFo