Reputation: 159
<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 cannot hide the div. So it worked only for showing not for hiding it? Any thing i did wrong? Thanks in advance.
Upvotes: 3
Views: 109
Reputation: 1690
You forgot an 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/
Upvotes: 4
Reputation: 520
If you got some spoilerS with a "s" you should use a class instead of an ID.
Then I recommend not to do it directly with JavaScript but to add a class hidden with the css display:none
property.
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";
}
}
}
Upvotes: 0
Reputation: 2750
function toggle () {
var div = document.getElementById('spoilers');
div.style.display = div.style.display === 'none' ? 'block' : 'none';
}
Upvotes: 2