Reputation: 421
I want to animate an object (in my example, a div), to move 100px from left to right, using JUST javascript (no JQuery allowed).
Here is my code http://pastebin.com/HvNjQES0.
function move(elem) {
var st = 0;
console.log("ELEM " + elem);
function animate() {
st++;
console.log(st);
elem.style.left = st + 'px';
console.log("elem" + elem.style.left);
if (st == 100) // check finish condition
clearInterval(id)
}
id = setInterval(animate, 10);
}
HTML:
<button onclick="move(text_ex)">Click</button>
<div id="text_ex" style="width:100px; height:100px; background-color:red"></div>
What is the problem with my code (it won't work)?
Any other solution is welcomed.
Upvotes: 0
Views: 2165
Reputation: 7339
Add position:absolute
to your div and it will work like a charm.
Upvotes: 1
Reputation: 5468
First, if you want to enable the div
movable, you need either set its display
style as absolute
or relative
.
Second, in you animate function, you need get the element by document.getElementById(elem)
";
Upvotes: 1