38

How do I get the amount of scroll in a div tag using JavaScript? Please provide me with an example.

I don't want to use jQuery, only JavaScript.

1
  • 19
    @Alex: ReferenceError: invalid assignment left-hand side. Seriously though, it's not accurate to say that - jQuery is a JavaScript library; the two are thus quite different. Commented Dec 7, 2010 at 6:11

2 Answers 2

41

Try this code snippet

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function scrollPos() {
            var div = document.getElementById("myDiv").scrollTop;
            document.getElementById("pos").innerHTML = div;
        }
    </script>
</head>
<body>
    <form id="form1">
    <div id="pos">
    </div>
    <div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scrollPos();">
        Place some large content here
    </div>
    </form>
</body>
</html>
Sign up to request clarification or add additional context in comments.

1 Comment

var div = document.getElementById("myDiv").scrollTop; this will not work in firefox
38

you use the scrollTop attribute

var position = document.getElementById('id').scrollTop;

1 Comment

If you are navigating in a horizontal scroll bar scrollLeft might be the property you need.

Your Answer

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