Sylar Sylar - 1 month ago 7
Javascript Question

No click event when rendering a js.erb partial

What happens to the dom when you re-render a partial with

js.erb
? I can no longer get click events.

Based on this tutorial, I have followed it to re-render a
js.erb
partial which works fine. When I click the "cat.name" button (on linked page), and on that page is another button that I'm listening for click events but not working.

The run down:

On index page, click event works. When I make the request for
from_category
, no more click event. So what really happen?

Html:

<button id="test" value="ok">click</button>


JS:

$( "#test" ).on("click", function(e) {
console.log(e.target.value)
});

Answer

You click events don't bind to the new dom elements you should use event delegation to bubble the events to the newly created dom elements

$('body').on('click input keypress','.the_dynamic_element',function(){

});