Scott B
Scott B

Reputation: 40157

jQuery click handler function does not fire on element added after DOM load

I believe I could do this with .live but that method is deprecated. Here's the issue:

I have a click handler function that should fire on any element with the class "myClickEl" for example. This works fine on "myClickEl" elements that are present in the document at the time its loaded. However, if I add a myClickEl element after the DOM has loaded, the click handler does not fire.

Here's the code. I've tried both methods below:

Option 1:

    jQuery('.myClickEl').on('click', function(){
        var formText='This is some text to paste';
        jQuery(this).parent().next('textarea').val('');
        jQuery(this).parent().next('textarea').val(formText);
    });

Option 2:

    jQuery('.myClickEl').click(function(){
        var formText='This is some text to paste';
        jQuery(this).parent().next('textarea').val('');
        jQuery(this).parent().next('textarea').val(formText);
    });

Upvotes: 6

Views: 4244

Answers (2)

useSticks
useSticks

Reputation: 904

From http://api.jquery.com/on/

You are interested in the usage of on:

.on( events [, selector ] [, data ], handler(eventObject) )

The example JQuery gives is

$( "#dataTable tbody" ).on( "click", "tr", function() {
    alert( $( this ).text() );
});

And you should do something similar, where you first select an element that will be static on the page and then the selector of where the click event should be used.

Best practice is to be as specific as possible, so try to choose a reasonable first target so that JS does not have to check every click event to see if it should run.

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You need to use Event delegation

jQuery(document).on('click','.myClickEl', function() { 
    var formText='This is some text to paste';
    jQuery(this).parent().next('textarea').val('');
    jQuery(this).parent().next('textarea').val(formText);
});

Upvotes: 12

Related Questions