bunkdeath
bunkdeath

Reputation: 2448

Toggling elements with JavaScript

I want to toggle a div element (expand/collapse) when clicked. I have many div elements, on click to new element, I want to collapse the previous one and expand the current clicked one.

I tried using static type variable to save the instance of previous div tag and compared with the current selection, but I don't know why is it not working.

Searching about this, I got similar code idea to collapse all div and then expand the current selected only, but I want to just toggle the previous one with new one, not collapse all div and expand the selected (though I would be using it if other way is not possible)

Can it be done using static variables of js?

Upvotes: 0

Views: 127

Answers (2)

Yi Jiang
Yi Jiang

Reputation: 50165

At its simplest, you can simply do something like this:

var divs = document.getElementsByTagName('div'),
    collapseClass = 'collapsed',
    current = divs[0];

// Hide all elements except first, add click event hander
for(var i = 0, len = divs.length; i < len; i++){
    divs[i].onclick = function(){
        if(this !== current){
            toggle(this, current);
            current = this;
        }
    };

    if(i > 0) toggle(divs[i]);
}

This will store the current element in a variable, then toggle it when another element is clicked. It also uses an if statement to check if the currently clicked element is the one currently visible element, and only toggles if its not.

See a working demo of this here: http://jsfiddle.net/GaxvM/

Upvotes: 1

tkone
tkone

Reputation: 22758

You can assign a unique ID to each of the elements and use document.getElementById to identify both elements, and then collapse one/expand the other.

If you number them sequentially (like div1, div2, div3, etc) you could do something like:

function colexp(div_id){
     div_2_collapse = document.getElementById(div_id);
     next_div = div_id.substr(0,3) + parseInt(div_id.substr(3))+1;
     div_2_expand = document.getElementById(next_div);
     hide(div_2_collapse);
     show(div_2_expand);
}

Upvotes: 0

Related Questions