Reputation: 31
I'm new to HTML, CSS and JavaScript, and I've stumbled upon a problem. This code should create a picture that's moving to the right over time, but it only works if I delete the doctype line of code. I've tried this code in the validator, it shows no errors, but it doesn't do what I want it to do unless I delete the doctype. What should I change here?
<!doctype html>
<html>
<head>
<title>Timer pomeranje</title>
<script>
var the_timer, x_position = 0, the_image;
function set_timer() {
the_image = document.getElementById("djuro_image");
x_position = x_position + 1;
the_image.style.left=x_position;
the_timer = setTimeout(set_timer, 50);
}
</script>
</head>
<body onload = "set_timer()">
<img src = "Djuro.png" id = "djuro_image" style = "position:absolute; left:0px" alt = "Djuro">
</body>
</html>
Upvotes: 2
Views: 456
Reputation: 46539
In Quirks mode (without a DOCTYPE declaration), CSS sizes without units are allowed; they are interpreted as pixels.
In Standards mode (with a DOCTYPE), CSS lengths always need units.
So the solution is to add px
to the position: the_image.style.left=x_position+'px';
Then it will work in both Standards and Quirks mode.
var the_timer, x_position = 0, the_image;
function set_timer() {
the_image = document.getElementById("djuro_image");
x_position = x_position + 1;
the_image.style.left = x_position + 'px';
the_timer = setTimeout(set_timer, 50);
}
set_timer();
<img src="Djuro.png" id="djuro_image" style="position:absolute; left:0px" alt="Djuro">
As a side note, using Quirks mode is never a good idea. In this particular case, most browsers share the same quirk (CSS size without a unit is treated as px) but that is not always the case!
Upvotes: 6
Reputation: 11819
You need to provide the unit, in your case 'px':
the_image.style.left=x_position + 'px';
here is the plunkr:
http://plnkr.co/edit/vyYUoItrw3S0eJyFa0wb?p=preview
Upvotes: 0