Search code examples
javascripthtmlcssscrolloffset

Changing the offset of div with javascript


I'm trying to create my own scroller and I have a long horizontal table contained in a div and I'm currently just trying to be able to move the div left or right.

I tried the following:

var d = document.getElementById("scroll");
d.style.color = "blue";
d.style.left = -300;

The color was to see if I could access the div from the scroll "class". It turns blue, however it's not able to offset left by 300, nothing happens.

What am I doing wrong?


Solution

  • I see three issues:

    1. The element is not positioned(left, right, top and bottom properties will work if the element is positioned). Alternatively, you could use marginLeft.
    2. -300 does not have quotes or double quotes around it.
    3. You are missing the units px.

    var d = document.getElementById("scroll");
    d.style.color = "blue";
    d.style.position = "relative";
    d.style.left = "-300px";