Reputation: 40157
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
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
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