Reputation: 14739
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
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
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
Reputation: 40639
Try to use off() like,
$("html").on("click keydown", function(e) {
alert(e.type);
$(this).off("click keydown");
});
Upvotes: 0
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