How to use scrollLeft?

Hi,

I must misunderstand something. I thought the following code will move the elements in body by 1000 and will show the number 1000:
document.body.scrollLeft=1000;   //Why nothing happened with this
alert(document.body.scrollLeft;     //Why this is zero?
johnwoodAsked:
Who is Participating?
 
TNameCommented:
Hi, first, use document.documentElement.scrollLeft.
Then, make the body wide enough. You can only set the scrollLeft property to a value that is smaller than or equal to the total width of the body tag minus the horizontal resolution in px. Try this:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style>
  body {width:3000px; height:600px; border:2px solid #c00; }
</style>
<script>
function test() {
  document.documentElement.scrollLeft=1000;  
  alert(document.documentElement.scrollLeft);      
}
</script>
</head>
<body onClick="test();">
  Click somewhere inside the red border...
</body>
</html>
0
 
hieloCommented:
Try:
document.all.getElementByTagName("body")[0].scrollLeft
Furthermore, I believe it works only for IE.
More info here:
http://www.java2s.com/Code/JavaScriptReference/Javascript-Properties/scrollLeft.htm

0
 
TNameCommented:
@hielo

   document.all.getElementByTagName("body")[0]
will not work as a way of accessing the body element. It should be
  document.getElementsByTagName('BODY')[0]  
so "document." instead of "document.all" and there should be a (plural) "s" - "Elements"...
0
 
johnwoodAuthor Commented:
Thank you hielo and TName!

TName,
I have just tried your code and it worked. However, if I delete the first line
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
it would not work anymore!!! Very strange!!!
0
 
TNameCommented:
That's due to the fact that IE will behave differently in this respect if in strict vs. quirks mode. Have a look e.g. here:
    http://www.quirksmode.org/viewport/compatibility.html
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.