On () does nothing with click event

I have a div with the identifier "close" inside a dynamically created div with the identifier "box". The following code is designed to do something whenever the user clicks on the close button.

$('#box').on('click','#close',function(){ alert(1); // Test to see if the click works }); 

I use CMS Big Cartel, and if I click "in preview mode", it works fine, but every time I actually publish a site and view it normally, it does absolutely nothing - no mistakes - nada.

Markup and CSS, just in case:

 <div id="box"> <!-- Dynamically loaded --> <div id="close"></div> <h2 id="name"></h2> <div id="description"> <p>blah...</p> </div> </div> #close{ background: url(image-path); float: right; position: relative; top: 0; margin: 0 0 0 12px; width: 25px; height: 25px; cursor: pointer; z-index: 100; } 

What am I missing?

+4
source share
3 answers

The problem is that #box also dynamic. For the primary selector, you need an element that is available when the page loads.

The primary candidate will be the item into which you upload #box .

+7
source

You need to bind to an existing element, not to a dynamically created one:

 $(document).on('click','#box #close',function(){ alert(1); // Test to see if the click works }); 

EDIT: the best solution is NOT to connect to the document :) avoids traversing the object.

 $("#boxesparentid").on('click','#close',function(){ alert(1); // Test to see if the click works }); 
+3
source

When you use event delegation (for example, using .on , how you do it), you bind the event to the element that is higher in the DOM , and then checks for every event that bubbles up to see if it matches the selector. The important part to implement is that you need to make sure that the element you are linking currently exists in the DOM (the one that bubbles up is not necessary).

In your case, since the field is also dynamic, the event is not tied to anything, instead you can bind to a document that exists, or to any element of a higher level that is currently in the DOM

for instance

 $(document).on('click','#close',function(){ alert(1); // Test to see if the click works }); 
+2
source

All Articles