Reputation: 23
This is supposed to change the position of a paragraph (with the id 'Text') more to the right each time it is looped. It doesn't work though and I can't figure out how to fix it, so I would be very happy if someone could help me. Thank you in advance.
var x = 0;
d.style.position = "absolute";
function myLoop () {
setTimeout(function () {
x += 10;
document.getElementById('Text').style.left = x+'px';
myLoop();
}, 100)
}
(This is everything in the script)
Upvotes: 2
Views: 576
Reputation: 7171
try this one
d
have not any value so define d
with
d = document.getElementById('Text');
and call your function myLoop
so its work
var x = 0;
d = document.getElementById('Text');
d.style.position = "absolute";
myLoop();
function myLoop() {
setTimeout(function() {
x += 10;
d.style.left = x + 'px';
myLoop();
}, 100)
}
<input type='text' id='Text'>
Upvotes: 1
Reputation: 122026
You have 2 issues here.
1) You have never defined d. That causing to stop the script right there without executing next lines of code.
2) You have never called myLoop()
function.
So with all corrections.
var x = 0;
var d = document.getElementById('Text');
d.style.position = "absolute";
myLoop();
function myLoop () {
setTimeout(function () {
x += 10;
d.style.left = x+'px';
myLoop();
}, 100)
}
<div id="Text">Test </div>
Besides this solution, you might have a to take a look at setInterval function which reduce your code a bit.
var x = 0;
var d = document.getElementById('Text');
d.style.position = "absolute";
myLoop();
function myLoop () {
setInterval(function () {
x += 10;
d.style.left = x+'px';
}, 100)
}
<div id="Text">Test </div>
Upvotes: 3