2

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>
2
  • you should not write your javascript in your head Commented Oct 18, 2015 at 20:40
  • You'll have to tell which browser you're using. Commented Oct 18, 2015 at 20:41

2 Answers 2

6

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the explanation, it works now :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.