2

guys, I am playing arround with HTML5 and javascript. The current thing which I am making is the following: there is a purple block on the screen and when you click a button it is moved 100 pixels to the right. This works so far, however, the function works only on the first time it is ran. I can't find my bug. I am posting the entire source code (javascript, html and css)

<!doctype html>
<head>
<style>
#stage{
    position: relative;
    width : 800px;
    height : 600px;
    background: #c0c0c0;
    border: 1px dashed black;
}

.coil{
    width: 64px;
    height: 64px;
    background:  #800080;
    position: absolute;
    top: 200px;
    left: 50px;
}
</style>
</head>


<body>
<div id="stage">
<div class="coil"></div>
<button id="button1">move!</button>
</body>
<script>
var coil = document.querySelector(".coil");
var button = document.querySelector("#button1");
button.addEventListener("click", clickHandler2, false);

//why is it working correctly just once
function clickHandler2()
{
    coil.style.left += 100 + "px";
}
</script>
3
  • 3
    Each time you're appending the string '100px' to the coil.style.left property. So on the second click you have invalid CSS. Commented May 17, 2013 at 16:40
  • Alright, how do I fix this ? Commented May 17, 2013 at 16:41
  • 1
    Just some notes: 1. You don't have html tag. 2. You don't close #stage tag. 3. You put script outside the body and it's invalid by HTML. Commented May 17, 2013 at 16:46

3 Answers 3

2

As nycynik mentioned, you are being a bit careless with the string additions.

Try this:

function clickHandler2()
{
    var before = parseInt(coil.style.left);
    before = isNaN(before) ? 0 : before;
    coil.style.left = before + 100 + "px";
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I will mark it as an answer when the system lets me.
Here is a working fiddle: jsfiddle.net/FAf4Q (some fine tuning needed though...)
2

When you do your add like that, its not actually adding to the value, its only making a new string; add a console.log on the button and you will see.

console.log(coil.style.left += 100 + "px");

the output is "100px100px"

one alternative solution:

var coilPos = 100;
//why is it working correctly just once
function clickHandler2()
{
    coilPos += 100;
    coil.style.left = coilPos + "px";
    console.log(coil.style.left += 100 + "px");
}

Comments

2

You must use a closure. A variable in the closure context must keep the left value. Then when applying the value to the property you use

var actualLeft += 100; coil.style.left= actualLeft +"px";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.