Remove / Reset JQuery Event Handlers

Posted By Weston Ganger

When working on ajax or turbolinks websites, if your not careful with which elements you bind events to it can result in additional event handlers being attached. This means your function will run as many times you have added the event again. I has an event that is bound to the document object like so:


$(document).on('click','.my-class',function(){...});

Now when that script gets added to the page again or even overwritten the event is still there because you bound it to the document itself which was not removed. To make sure that you dont have double event handlers running add the .off() function just before it.


$(document).off('click','.my-class');
$(document).on('click','.my-class',function(){...});


Related External Links:

Article Topic:Software Development - Javascript

Date:October 13, 2015