Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.live() Handlers Firing Multiple Times

I have to generate some buttons dynamically based on some service response, and also have to attach some handlers on click of those buttons. So I am using jQuery.live() for it, it works well for the first time.

But when i removes all buttons using jQuery("<some container div>").empty() and creates again those buttons, now on click of button "handler calls twice", if I repeat the same it fires thrice and and same.

Can you guys help me, thanx in advance.

like image 319
santosh kore Avatar asked Dec 09 '22 15:12

santosh kore


2 Answers

$().live() was depreciated in jQuery 1.7 and removed in 1.9

Or try something like

$('#button').die('click').live('click', function(e) {
        alert('Button click');
    }); 
like image 120
ANonmous Change Avatar answered Dec 11 '22 08:12

ANonmous Change


Follow jquery website jquery.live() :

Attach an event handler for all elements which match the current selector, now and in the future.

That's mean : the event that you attach with live will be applied for all element that have same selector. So you must check the event of element and just attach new element if it's not available.

$("SELECTOR").live('click',function(e){
         //check the event is already set
         e.preventDefault();
         if(e.handled === true) return false;
         e.handled = true;   

         //Do something here
         //YOUR CODE HERE

         return false;
    });
like image 41
JamesN Avatar answered Dec 11 '22 10:12

JamesN