I have a bunch of items setup with <div id="first" class="source">
I'm in Google Chrome, and when page loads it hides those items when I click the OnClick button it will un hide them, but I'm not able to click it again and make it hide.
HTML
<body onload="setup();">
<a href="#first" onClick="shoh('first');" >
JS:
function setup() {
foo = document.getElementById('first');
foo = document.getElementsByClassName('source');
for (c=0; c<foo.length; c++) {
foo[c].style.display='none'
}
}
function shoh(id) {
if (document.getElementById(id).style.display = 'none'){
var divs = document.getElementById(id);
for(var i=0; i<divs.length; i++) {
divs[i].style.display='block'
}
} else {
cow = document.getElementById(id);
for(a=0; a<cow.length; a++) {
cow[a].style.display='none'
}
}
}
You have a couple of issue here:
If you compare two variables you need to use ==
, so therefore it should be:
document.getElementById(id).style.display == 'none'
Also, you are using getElementById
, which returns a single node, not an array. So therefore you should not loop over the returned value:
var div = document.getElementById(id);
div.style.display='block';
So in the end, it should look like this:
function shoh(id) {
if (document.getElementById(id).style.display == 'none'){
var div = document.getElementById(id);
div.style.display='block';
} else {
cow = document.getElementById(id);
cow.style.display='none';
}
}
Your conditional isn't doing a comparison. You need to change
if (document.getElementById(id).style.display = 'none'){
to
if (document.getElementById(id).style.display == 'none'){