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);
});
Update Mouse Drivers It's prudent to make sure your mouse drivers are always up-to-date. If the left click isn't working, you definitely need to check them. Right-click on the Start Menu and then choose Device Manager. Don't worry: you can also use the right-click button to make your selection.
on() differs from . click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas . click() does not.
JQuery OnClick Method is bound to an element or selector on page ready/load. Therefore if that element you want to click isn't there at the time of page ready, the binding can't happen.
jQuery unbind() MethodUse the off() method instead. The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.
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);
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With