简体   繁体   中英

Toggle multiple divs on and off (almost working)

I have this:

function toggleCharts() {
var x, divArray = ["item_4746983", "item_4491867"];
for (x in divArray) {
    if (x) {
        document.getElementById(divArray[x]).style.display = 'block';
    }
}

<button onClick="toggleCharts();">Charts</button>

and this:

#item_4746983 {
    display:none;
}

#item_4491867 {
    display:none;
}

item_4746983 & item_4491867 are thumbnails that I want to show or hide when you click on charts

The code works and they display when I click the button but I can't figure out the code to hide them by clicking on it again.

Instead of styling by id, style by class:

.hiddenThumbnail {
    display:none;
}

Then apply and remove the hiddenThumbnail class to and from the two items. This makes your css code smaller, and makes everything generally more maintainable. See this excellent answer for a guide on how to modify the classes.

Alternatively, use a library like YUI to do it (I'm sure jquery has similar functions also).

Check if the div is shown already and change the display. The following code should work.

var div = document.getElementById(divArray[x])
var shown = div.style.display;

if ("block" == shown) {
    div.style.display = none;
} else {
    div.style.display = block;
}

Here is a link that shows various ways of doing what you want: http://www.dustindiaz.com/seven-togglers/

Check the demo .

function toggleCharts() { 
    var divArray = ["item_4746983", "item_4491867"], i, ele;
    for (i=0; i < divArray.length; i++) {
        ele = document.getElementById(divArray[i]);
        ele.style.display = ele.style.display === 'block' ? 'none' : 'block';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM