Reputation: 131
I know this may have already been answered but I haven't been able to find one that quite fits what I'm trying to do. Pretty much I want to make a div slide to the side after 2 seconds using js. This is what I have now;
setTimeout("slide()", 1000)
function slide() {
var myElement = document.querySelector("#box");
myElement.style.left = 200px;
setTimeout("slide()", 2000)
};
#box {
position: absolute;
left: 100px;
top: 100px;
width: 300px;
height: 300px;
background: blue;
}
<div id="box">box</div>
Anything I'm doing wrong or a link to a question that answers this would be a big help! Thanks
Upvotes: 0
Views: 126
Reputation: 34227
Not properly using setTimeout
function. Use style string.
setTimeout(function(){slide();}, 1000);
function slide() {
var myElement = document.querySelector("#box");
myElement.style.left = "200px";
setTimeout(function(){slide();}, 2000);
}
or simply
setTimeout(slide, 1000);
function slide() {
var myElement = document.querySelector("#box");
myElement.style.left = "200px";
setTimeout(slide, 2000);
}
Why use the first option? Pass parameters that way:
setTimeout(function(){slide(2000);}, 1000);
function slide(delaytime) {
var myElement = document.querySelector("#box");
myElement.style.left = "200px";
setTimeout(function(){slide(delaytime);}, delaytime);
}
Upvotes: 0
Reputation: 11369
setTimeout takes a function as its first argument, but you pass a string. Even if it wasn't a string, it would misfire, because of the ()
The proper way to use setTimeout is like this:
setTimeout(slide, 1000);
function slide() {
var myElement = document.querySelector("#box");
myElement.style.left = '200px'; // Fix this too!
setTimeout(slide, 2000)
};
Upvotes: 0
Reputation: 37813
Where you have:
myElement.style.left = 200px;
It should be:
myElement.style.left = '200px';
Also this:
setTimeout("slide()", 2000);
Should really just be this:
setTimeout(slide, 2000);
Upvotes: 1