Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(document).on("click"... not working?

Tags:

jquery

click

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?

like image 326
Mr. Lavalamp Avatar asked Jul 11 '13 23:07

Mr. Lavalamp


People also ask

Why on click is not working jquery?

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.

Why click is not working?

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.


1 Answers

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:

  • Not using recent version of jQuery
  • Not wrapping your code inside of DOM ready
  • or you are doing something which causes the event not to bubble up to the listener on the document.

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

like image 70
itsmejodie Avatar answered Sep 20 '22 10:09

itsmejodie