AddEventListener on javascript unlock activation
I want to run a function countup();
and random();
after I hit enter on my keyboard. But I want to make it work the first time only. I mean, the first time I hit enter, it will trigger this function. But if these functions are already running and I hit Enter again, it won't do anything.
Here's my code:
addEventListener("keydown", function(e){
if (e.keyCode === 13) {
countup();
random();
}
});
Can anyone help me? Thank.
source to share
Do something like this
// Create a named function as your event handler
var myFunction = function (e) {
if (e.keyCode === 13) {
// Do your stuff here
countup();
random();
// Remove event listener so that next time it is not triggered
removeEventListener("keydown", myFunction);
}
};
// Bind "keydown" event
addEventListener("keydown", myFunction);
source to share
You can make the click event listener only run once after starting it. You just need to add another argument to addEventListener()
which is equal {once:true}
and it will work as expected:
addEventListener("keydown", function(e){
if (e.keyCode === 13) {
countup();
random();
}
},{once: true});
Check this question for my version similar to your case.
Also you can just use the method removeEventListener()
, but you have to define the function of the anonymous one earlier as an external function of the type myKeyPressed()
and then internally if the condition removes the Listener event from your element:
element.removeEventListener("keydown", myKeyPressed);
source to share
There is a removeEventListener function in javascript, but it is difficult to implement this inside the function that you call in addEventListener. Try this, it worked in jsfiddle.
addEventListener("keydown", function(e){
if (e.keyCode === 13) {
alert("i did it");
this.removeEventListener('keydown',arguments.callee,false);
}
});
source to share