Javascript toggle button not working
<input tyoe="button" onclick="toggle()" value="Show Spoilers" />
<div id="spoilers" style="display: none;">Some spoilers</div>
<script>
function toggle(){
var div = document.getElementById("spoilers");
if(div.style.display = "none"){
div.style.display = "block";
} else {
div.style.display = "none";
}
}
</script>
it worked to show but can't hide the div. So it only worked so as not to show it? Any thing I did wrong? Thanks in advance.
+3
source to share
3 answers
You forgot equal (=) in your if
function toggle()
{
var div = document.getElementById("spoilers");
if(div.style.display === "none"){
div.style.display = "block";
} else {
div.style.display = "none";
}
}
Example: http://jsfiddle.net/90Lw12cf/
+4
source to share
If you have spoilers with "s" you should use class instead of ID.
Then I recommend not to do it directly from JavaScript, but add a class hidden with a css property display:none
.
function toggle(){
var divs = document.getElementsByClassName("spoilers");
for(var i = 0; i > divs.length i++){
if(divs[i].classList.contains("hidden")) {
divs[i].classList.remove = "hidden";
} else {
divs[i].classList.add = "hidden";
}
}
}
0
source to share