Question

Here's a little demo of what I'm experiencing:

http://jsfiddle.net/jajV6/

And here are the code snippets:

HTML:

<div id="frame">
<div class="bead col_a" id="a1"></div>
</div>

CSS:

#frame {
position: relative;
height: 205px;
}

.bead {
position: absolute;
background: black;
width: 50px;
height: 25px;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
}

.bead:hover {
background-color: white;
border: 1px solid black;
}

#a1 {
top: 0px;
}

JS:

var a1 = document.getElementById("a1");

function fiveToggle(bead1) {
    if (bead1.style.top === "0px"){
    bead1.style.top = "25px";
    } else {
    bead1.style.top = "0px";
    }
}

a1.addEventListener("click", function(){ fiveToggle(a1); }, false);

The idea is to have the position of the bead shift either up or down when clicked. To toggle, in other words. But adding an if/else statement to the function that achieves this makes the clickable item require two clicks before it will move. After that initial extra click, the bead moves with one click as desired. If I remove the if/else statement from the function that repositions the bead and add code that simply moves it (without a conditional check), then it works as desired. I find this curious. Would someone kindly explain to me why this behaves this way?

Was it helpful?

Solution

There is no problem with addEventListener, you have to add one condition || bead1.style.top == "" because bead1.style.top is empty by default:

function fiveToggle(bead1) {
    if (bead1.style.top == "0px" || bead1.style.top == ""){
        bead1.style.top = "25px";
    } else {
        bead1.style.top = "0px";
    }
}

You can do that using css too, setting the initial top value to 0px

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top