Liam Sperry
Liam Sperry

Reputation: 13

why is the if statement not working in js

window.addEventListener("keyup", addkey);

function addkey(){
		var x = event.which || event.keyCode;
		var wkey = 0;
		var op = 0;
		
		if(x == 87){
			wkey += 1;
		}
		if(wkey == 1 && op == 0){
			alert("your doing good!");
			op = op + 1;
		}
	}

What im trying to get to happen here is getting the alert statement to run once and only once but i cant get it to work either way. I tried using a true or false numberical system (the op variable) but that dident work either. What i see happening is when the code runs and the keyup event fires the wkey variable updates once and stays 1 even know it should be going up a numeral each time the w key is pressed. Anyway i am making this code to go along with a tutorial for the game im making. Any and all suggestions i am open to.

Upvotes: -1

Views: 77

Answers (3)

Unknown
Unknown

Reputation: 44

Each time the function is called,

wkey gets set to 0,

and then 1 is added,

so it will always end up being equal to 1

Try defining wkey as 0 outside of the function.

Or having

if(wkey == null) var wkey = 0;

instead.

If you use this method op is unnecessary. (Unless of course you're using it's value elsewhere.)

Upvotes: 0

Keiwan
Keiwan

Reputation: 8251

This happens because you re-initialize op to 0 every time the function gets called. You can simply delcare op outside of addkey and it will work:

window.addEventListener("keyup", addkey);
var op = 0;
var wkey = 0;

function addkey(event){
    var x = event.which || event.keyCode;
    
    if(x == 87){
        wkey += 1;
    }
    if(wkey == 1 && op == 0){
        alert("your doing good!");
        op += 1;
    }
}

You'll also need to pull the declaration of wkey out of the function if you want to successfully count how many times it was pressed.

Upvotes: 3

Mateusz Woźniak
Mateusz Woźniak

Reputation: 1499

That's because you define wkey and op on each function run, you should define them out of the function, to make it work as expected.

Upvotes: 0

Related Questions