Semger
Semger

Reputation: 263

Best way to check a variable jQuery

I have a script which checks is a variable is set or is equal to 'no'. If it is equal to no or is not set, it defines the var to be 'yes'.

This is my code

if (typeof progress == 'undefined' || progress == 'no') { 
document.getElementById('button-play').onclick = null;
var progress = 'yes';

Then a function is called which overwrites the variable to be no.

function enableButton(){
var progress = 'no';
document.getElementById('button-play').onclick = play();
}

The first time when executing the script and progress is undefined, the script works, and does overwrite progress to 'no', but when I try to run the script again with var progress defined as 'no' it does not work.

Am I checking the value of progress correctly?

Added jsfiddle: https://jsfiddle.net/zxxubopq/

Upvotes: 0

Views: 82

Answers (4)

meskobalazs
meskobalazs

Reputation: 16041

The scope in Javascript is either Global or Function. If you define a variable in function, it'll be scoped in that function only.

That does not override the varible, it is a different, local progress variable in the scope of enableButton(). You should fix your scopes, and it will work.


Edit after your comment:

document.getElementById('button-play').onclick = play();

is actually wrong, because you want to assign the function to onclick, not the return value, so you actually need:

document.getElementById('button-play').onclick = play;

Remember, JavaScript functions are first-class functions, so they can be treated just like any other object.

Upvotes: 2

Hemal
Hemal

Reputation: 3760

Declare variable 'progress' outside both function at start.

Upvotes: 0

Fabjan
Fabjan

Reputation: 13676

function enableButton(){
  var progress = 'no';
}

This line of code creates new variable var progress inside function. So when function exits this variable is deleted.

Try to change it to:

function enableButton(){
    progress = 'no';
}

Upvotes: 1

dersvenhesse
dersvenhesse

Reputation: 6404

Your var inside a function makes the variable progress a local one. So any changes to the local variable don't apply for the global one.

Upvotes: 2

Related Questions