jQuery On function for future elements?

17,029

Solution 1

For future elements inside #dataTable tbody, your code should work. To delegate the click all the way up to the document, allowing the same handler for future <tr> anywhere on the page, try:

$(document).on("click", "tr", function(event){
    alert($(this).text());
});

Solution 2

Adding to Davids accepted answer, you can also use this solution to bind multiple events to a selector as well as all future matching elements.

For example an input element.

$(document).on({
    focus:function(){
        alert($(this).val());
    },
    blur: function(){
        alert($(this).val());
    }
}, 'input[type=text]');

Solution 3

This will handle all <tr>s, no matter when they were created, but only within the currently-existing #dataTable tbody.
It's equivalent to .delegate.

Share:
17,029

Related videos on Youtube

Royi Namir
Author by

Royi Namir

Updated on June 04, 2022

Comments

  • Royi Namir
    Royi Namir almost 2 years
    $("#dataTable tbody").on("click", "tr", function(event){
        alert($(this).text());
    });
    

    is this syntax is for tr's which are already on the Page ?

    and if not , What is the syntax for future tr's elements ?

  • Royi Namir
    Royi Namir over 12 years
    So there is no difference anymore between "already in dom" vs "will be in dom" ?
  • Stefan
    Stefan over 12 years
    There are still differences but delegate(), live() and on() can handle both.
  • Royi Namir
    Royi Namir over 12 years
    @Stefan since 1.7 I should not use live anymore and delegate is like on.... so there is no difference anymore ......right?
  • Royi Namir
    Royi Namir over 12 years
    so what youre saying is that the "on" is also for current and future dom ?
  • Stefan
    Stefan over 12 years
    You´re right, you shouldn´t use live() since 1.7 but delegate() and on() can handle a modified DOM which click() doesn´t.
  • David Hellsing
    David Hellsing over 12 years
    Yes, as long as the inserted element is inside the element that bound the event.
  • Reign.85
    Reign.85 almost 10 years
    Exactly what i needed. I love you
  • Gavin
    Gavin over 8 years
    @RoyiNamir there is a difference. Using syntax like $('.container elem').on('click', function(){}) is only for current elements. Using syntax like $('.container').on('click', 'elem', function(){}) handles future elements as well.