Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery event handler to execute only once the is bound to multiple elements

Tags:

jquery

I want to have an event handler that executes only once and then unbinds itself from all the elements it was bound to.

I know of .one() but when using it "The handler is executed at most once per element".

Is there a "built-in" way to bind an event handler to multiple elements and have it removed automatically from all of the once it is executed on any one of them?

like image 259
epeleg Avatar asked Feb 23 '26 12:02

epeleg


2 Answers

Easy. Just unbind the event handler inside the callback function. Like this:

$('p').on('click', function(){
  alert('I appear only one time');
  $('p').off('click'); // Removes the event. So, it will never be executed again.
})

This script will remove all events of type click, and that is a bit aggresive. Check the documentation for off and unbind for more info.

like image 104
miguel.camba Avatar answered Feb 26 '26 03:02

miguel.camba


miguel camba already told you to check the wiki for unbind. The correct solution would be the following:

    var handler = function() {
        alert('I appear only one time');
         $('p').unbind('click', handler);
    }
    $('p').bind('click', handler);

This will unbind only this handler from the click event.

//Edit:

Another solution would be to namespace your click event:

$('p').bind('click.myClickEvent', function() {
    alert('I appear only one time');
    $('p').unbind('click.myClickEvent');
});
like image 28
Jochen Ullrich Avatar answered Feb 26 '26 01:02

Jochen Ullrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!