afield
afield

Reputation: 283

using a button to switch between two states

Essentially I want to use a button to bring a div to the front using the CSS z-index and then when pressing the button again I want it to revert back to its original state.

This is the code I have got so far and it will happily change it first time round but it wont revert it back.

function thumbnail(){
    if (document.getElementById("div").style.zIndex= -3){
        document.getElementById("div").style.zIndex= -2;
    }

    if  (document.getElementById("div").style.zIndex= -2){
        document.getElementById("div").style.zIndex= -3;
    }       
}

Upvotes: 4

Views: 1993

Answers (2)

HBP
HBP

Reputation: 16043

This slightly more efficient version avoids traversing the DOM more than once:

function thumbnail () {
    var elStyle = document.getElementById ("div").style;
    elStyle.zIndex = elStyle.zIndex == -3 ? -2 : -3;
}

Using div as an id may prove to be confusing when you return to this code later, use a name which identifies the function of the div.

Upvotes: 0

pbibergal
pbibergal

Reputation: 2921

function thumbnail(){
    var depth = document.getElementById("div").style.zIndex;
    document.getElementById("div").style.zIndex = (depth == -3)? -2 : -3;
}

Upvotes: 4

Related Questions