Hoffmann
Hoffmann

Reputation: 14739

How to trigger callback on multiple events only once in jQuery

I need to do something only once when the user clicks on the page OR any key is pressed down. I would usually do this using the .one() function in jQuery, but the callback is called for both events once instead of only one time total:

$("html").one("click keydown", function() {
   alert("event");
});

I can't call $(this).unbind("click keydown") because I do not want to unbind the other events that might be bound to the element.

Edit: I should had mentioned this before but the code that binds the event is called multiple times and I want the callback to run one time for each time it was binded. If the event was binded n times I want the callback to run n times.

Upvotes: 1

Views: 3317

Answers (4)

Matt
Matt

Reputation: 75327

You could also write your own plugin for jQuery, which would handle this quite nicely;

jQuery.fn.onceFor = function (events, func) {
    var that = this;

    this.on(events, function () {
        that.off(events, func);

        return func.apply(this, arguments);
    });
};

... which you'd then call via;

$("html").onceFor("click keydown", function() {
   alert("event");
});

Upvotes: 0

Epsil0neR
Epsil0neR

Reputation: 1704

you can create your function outside event handler:

var onClickAndKeydown = function(){
    alert("event");
}

then add handler to events click and keydown to that function using .on():

$("html").on("click keydown", onClickAndKeydown);

and when you need, you can remove event handler for that function using .off():

$("html").off("click keydown", onClickAndKeydown);

The .off() method removes event handlers that were attached with .on(). If you specify address to your function inside .off(), then will be removed handler only to that function, so handlers for other functions still will be handled.

Upvotes: 1

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try to use off() like,

$("html").on("click keydown", function(e) {
   alert(e.type);
   $(this).off("click keydown");
});

Demo

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388436

Use namespaced event names

$("html").one("click.myonce keydown.myonce", function () {
    console.log("event");
    $(this).off('click.myonce keydown.myonce')
});

Demo: Fiddle

Upvotes: 0

Related Questions