Reputation: 91
I am trying to set a CSS property back and forth using JavaScript depending on its value.
The class name menu
is set to be hidden on page load. When I call the function to set it to visible it is successful. However, when I call it again to change it back it doesn't set it to hidden. It is seen as always set to visible.
let menu = document.querySelector('.menu');
if (menu.style.visibility = 'hidden') {
menu.style.visibility = 'visible';
console.log('visible'); // always shows this.
} else {
menu.style.visibility = 'hidden';
console.log('hidden'); // doesn't get to here when .menu is visible.
}
I am confused as to why it can do the first but not the second. I have tried using a else if
condition:
else if (menu.style.visibility = 'visible')
I also tried using the setAttribute
method but it's always the same outcome.
I need to be able to switch back and forth.
Upvotes: 0
Views: 88
Reputation:
The error is in your if statement. So if you change the single equality to a double equal sign: ==
, your code should work:
like:
if (menu.style.visibility == 'hidden')
Upvotes: 0
Reputation: 147
This code will toggle the visibility of a div on your page.
function togglediv() {
var div = document.getElementById("menu");
div.style.display = div.style.display == "none" ? "block" : "none";
}
<button onclick="togglediv('menu')">Toggle div</button>
<div id="menu">div</div>
Upvotes: 0
Reputation: 514
In JavaScript by using =
you assign a value to something BUT if you use ==
you are checking if something is equal to something else.
let menu = document.querySelector('.menu');
if (menu.style.visibility == 'hidden') {
menu.style.visibility = 'visible';
console.log('visible'); // always shows this.
} else {
menu.style.visibility = 'hidden';
console.log('hidden'); // doesn't get to here when .menu is visible.
}
Upvotes: 2
Reputation: 755
Your syntax for comparing is wrong you need to use ==
while comparing any field in javascript so just do :
if (menu.style.visibility == 'hidden') {
menu.style.visibility = 'visible';
console.log('visible'); // always shows this.
} else {
menu.style.visibility == 'hidden';
console.log('hidden'); // doesn't get to here when .menu is visible.
}
Upvotes: -2
Reputation: 23654
Your conditional isn't valid. You're actually setting the value in the if statement.
if (menu.style.visibility = 'hidden') // this sets the value
It should be this:
if (menu.style.visibility == 'hidden') // this compares the value
Upvotes: 0
Reputation: 1140
Kindly use below condition
if (menu.style.visibility == 'hidden') //change ==
Upvotes: 1