Reputation: 1
I'm new to javascript, so please help me to understand what is my problem.
setTimeout(function() {
var wide = false;
if(wide = false) {
document.querySelector(".some-class").onclick = function() {
document.querySelector("#some-id").className += " MyClass";
wide = true;
};
}
else {
document.querySelector(".some-class").onclick = function() {
document.querySelector("#some-id").className =
document.querySelector("#some-id").className.replace(/\bMyClass\b/,'');
wide = false;
};
}
}, 1000);
This is not working(not adding MyClass). But if I use just this:
setTimeout(function() {
document.querySelector(".some-class").onclick = function() {
document.querySelector("#some-id").className += " MyClass";
};
}, 1000);
Then it works fine. So what is the problem with my code that not working?
PS: Thank you. This what I got:
setTimeout(function() {
var wide = false;
if(wide == false) {
document.querySelector(".some-class").onclick = function() {
document.querySelector("#some-id").className += " MyClass";
wide = true;
};
}
else {
document.querySelector(".some-class").onclick = function() {
document.querySelector("#some-id").className =
document.querySelector("#some-id").className.replace(/\bMyClass\b/,'');
wide = false;
};
}
}, 1000);
It worked, but now it only add the MyClass on each onclick event and not removing it. I tried to play with else to elseif and tried to move the wide = flase
and wide = true
outside the onclick event, but yet this is the same.
Upvotes: 0
Views: 32
Reputation:
The issue is that you have: if (wide = false) {...
This is setting wide
equal to false
, not comparing values.
To compare values use ==
or ===
.
Single equals -> Defining/setting variables.
Double equals -> Comparison with type conversion. Ex: ("2" == 2) // true
Triple equals -> Comparison with no type conversion. Ex: ("2" === 2) // false
For your issue, you can use either double or triple equals.
Upvotes: 1
Reputation: 12129
change to if(wide === false) {...}
If you use =
you are setting wide
equal to false
, not comparing the two values for equality. In your case you can either use ==
or ===
to check for equality.
The former (==
) only compares values, while the latter (===
) compares values + type.
Upvotes: 0