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.
Idea is a global user variable that sets it upon startup.
var is_fired = false;
addEventListener("keydown", function(e){
if (e.keyCode === 13 && is_fired == false) {
countup();
random();
is_fired = true
}
});
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);
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);
var is_clicked = false;
addEventListener("keydown", function(e){
if (e.keyCode === 13 && !is_clicked) {
countup();
random();
is_clicked = true;
}
});
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);
}
});
You can add a variable to check the status of your key. The first time you use it, set it to true. Thus, you will only run this function once.
var n = document.getElementById("txtInput"),
r = document.getElementById("result"),
loadFlag = true;
n.addEventListener("keyup", function(e) {
if (e.keyCode === 13 && loadFlag ) {
countup(r);
random(r);
loadFlag = false;
}
}, false);