Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery click doesn't work on ajax generated content

I am using $(".button").on("click", function(){ });

to click to a button which is on a container but then an ajax call is done and the content gets updated with new stuff and then when i try to click .button it wont work... nothing will get returned when i click the button.

I even tried

$(".button").live("click", function(){ }); 

or

$(".button").click(function(){ }); 

How can I make it work?

EDIT : my html:

<div class="container">    <ul>        <li>item1</li>        <li>item2</li>        <li>item3</li>    </ul>    <input type="button" value="reload" class="button" /> </div> 
like image 599
stergosz Avatar asked Feb 18 '12 21:02

stergosz


People also ask

Why click function is not working in jQuery?

Be sure there is nothing on your button (such a div or a trasparent img) that keeps from clicking the button. It sounds stupid, but sometimes we think that jQuery is not working and all that stuffs and the problem is on the positioning of DOM elements. or, for example, z-index!

How do you bind events on ajax loaded content?

The jQuery events (click, change, blur, hover, submit, etc) need to be bind properly in the dynamic content loaded by the Ajax request. You need to use the event delegation for Ajax generated content using jQuery. Use jQuery delegation to attach an event in the dynamically created content by Ajax.

Why JavaScript not working after ajax response is received?

On the page allows filtering of products ajax. After receiving a response from the server and inserting it on the page stops working the script with hover effect.

What triggers ajax success?

AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.


1 Answers

Should be done this way.

$('body').on('click', '.button', function (){         alert('click!');     }); 

If you have a container that doesn't change during the ajax request, this is more performant:

$('.container').on('click', '.button', function (){         alert('click!');     }); 

Always bind the delegate event to the closest static element that will contain the dynamic elements.

like image 78
gdoron is supporting Monica Avatar answered Sep 19 '22 18:09

gdoron is supporting Monica