How to overwrite jquery event handlers

JqueryEvent Handling

Jquery Problem Overview


I'll try to explain the problem with a simple code.

var fireClick = function() { alert('Wuala!!!') };

$('#clickme').click(fireclick);
$('#clickme').click(fireclick);

So now it will obviously alert 2 times but i need it alert only once. Tried so many ways, but no result.

Thanks.

Jquery Solutions


Solution 1 - Jquery

As of jQuery 1.7 you should be using off to remove event handlers and on to add them, though you can still use the click shorthand.

$('#clickme').off('click').on('click', fireclick);
$('#clickme').off().on('click', fireclick);

Original answer:

If you want to replace all click handlers, call unbind first without a function argument. If you want to replace all event handlers, don't specify the event type.

$('#clickme').unbind('click').click(fireclick);
$('#clickme').unbind().click(fireclick);

Solution 2 - Jquery

Use a namespace to make sure you don't remove any other listeners:

$('#clickme').off('click.XXX').on('click.XXX', fireclick);

As long as no other code uses XXX, you can be sure that you have not messed up some other behaviour that you weren't aware of.

Solution 3 - Jquery

You may use the jQuery function unbind to remove the first event:

var fireClick = function() { alert('Wuala!!!') };

$('#clickme').click(fireclick);
$('#clickme').unbind('click', fireClick); // fireClick won't fire anymore...
$('#clickme').click(fireclick); // ...but now it will

Solution 4 - Jquery

I would try to eliminate the extra calls, but short of tyhat you could make sure to call both of these each time:

$('#clickme').unbind('click', fireclick);
$('#clickme').click(fireclick);

Solution 5 - Jquery

$(document).off('click', '#clickme').on('click', '#clickme', fireclick);

Solution 6 - Jquery

You should use setInterval. The problem is that you cannot have two alerts pop at the same time. First one has to close first or the second one can't appear on screen...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontarasView Question on Stackoverflow
Solution 1 - JquerytvanfossonView Answer on Stackoverflow
Solution 2 - JqueryNeil StevensView Answer on Stackoverflow
Solution 3 - JquerymoffView Answer on Stackoverflow
Solution 4 - JqueryMark RenoufView Answer on Stackoverflow
Solution 5 - JqueryHassan EjazView Answer on Stackoverflow
Solution 6 - JqueryLeroyVView Answer on Stackoverflow