Using Js To Move A Div Around The Page
Solution 1:
Based on the refined post, I now see that you are trying to access body content in the head with var x = document.getElementById("cr001").style.left;
This won't work because when the head is loaded, the body is not ready. You should make an init() function that looks like:
functioninit(){
window.x = document.getElementById("cr001").style.left;
window.y = document.getElementById("cr001").style.top;
moveImage();
}
and then attach that to the body onload.
EDIT: ok, here is some modified code that does what you want. You can stick this in a file named index.html and launch it in Firefox. I broke it down for you:
<html><head><scriptlanguage="javascript">var d_x = 75;
var d_y = 100;
var interval = 2;
//init is used for getting things up and running once the page is loadedfunctioninit(){
//optimization: only get the element oncevar el = document.getElementById("cr001")
x = parseInt(el.style.left);
if(isNaN(x)){
//parseInt("") == NaN
x = 0;
}
y = parseInt(el.style.top);
if(isNaN(y)){
//ditto
y = 0;
}
//call the nuts of this scriptmoveImage();
}
//this is mostly unchangedfunctionmoveImage() {
if(x < d_x){
x = x + interval;
}else{
//lets keep looping just for fun!
x = 0;
}
if(y < d_y){
y = y + interval - 1; //move y by only 1px
}else{
y = 0;
}
//optimization: only get the element oncevar el = document.getElementById("cr001")
el.style.left = x + 'px'; //dont forget to add 'px' back in
el.style.top = y + 'px';
//loop, don't use strings in setTimeout since this is basically eval...eval is evilsetTimeout(moveImage, 100);
}
</script></head><bodyonload="init()"><divid="container"><!-- IMPORTANT: POSITION IS ABSOLUTE --><divid="cr001"style="position:absolute; width:10px; height:10px; background-color:black"></div></div></body>
Solution 2:
The problem is here:
document.getElementById("cr001").style.left
This actually returns the css value, which is a string for example '100px' or '10%' etc. Yet, later on your code, you use this value as if it was an integer.
Solution 3:
You have an unclosed div. You open <div id="container">
and <div id="cr001" class="twinkles">
but only close one of them
Post a Comment for "Using Js To Move A Div Around The Page"