Is there a well-known mistake I could be making here?
I've got a script that's using .on() because an element is dynamically generated, and it isn't working. Just to test it out, I replaced the selector with the dynamic element's wrap, which is static, and it still didn't work! When I switched to plain old .click for the wrap it worked, though.
(This just won't work for the dynamic element obviously, the one that matters.)
This works:
$("#test-element").click(function() { alert("click"); });
This doesn't:
$(document).on("click","#test-element",function() { alert("click"); });
UPDATE:
I right-clicked and did "Inspect Element" in Chrome to just double-check something, and then after that the click event worked. I refreshed and it didn't work, inspected element, and then it worked. What does this mean?
The fix is easy enough, simply bind the OnClick event to the parent of the elements you want to be able to click on. That way, if the element you want to click on is removed and re-appended, the handler will still be there listening as the parent was never removed.
To turn it on, go to Start > Settings > Devices > Mouse > Related Settings > Additional Mouse Options. The Mouse Properties window will pop up. At the bottom of the Buttons tab, you'll see the ClickLock options. Put a tick in the checkbox to enable it.
You are using the correct syntax for binding to the document to listen for a click event for an element with id="test-element".
It's probably not working due to one of:
To capture events on elements which are created AFTER declaring your event listeners - you should bind to a parent element, or element higher in the hierarchy.
For example:
$(document).ready(function() { // This WILL work because we are listening on the 'document', // for a click on an element with an ID of #test-element $(document).on("click","#test-element",function() { alert("click bound to document listening for #test-element"); }); // This will NOT work because there is no '#test-element' ... yet $("#test-element").on("click",function() { alert("click bound directly to #test-element"); }); // Create the dynamic element '#test-element' $('body').append('<div id="test-element">Click mee</div>'); });
In this example, only the "bound to document" alert will fire.
JSFiddle with jQuery 1.9.1
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