JavaScript method of the day: scrollIntoView()

This little guy isn't actually part of w3c spec, but it is supported by IE and Firefox and can be very handy. This method is inherited by any visible DOM element and when it is called will cause the page/frame/div to scroll until that element is in view.

I'll admit, I've only use the bugger once, but it is surely useful. There's really not much else to say about it. The example where I used it is at http://www.diamondtbucket.com/index.cfm?do=parts. When using the "Previous" and "Next" buttons in the upper right corner of the screen, the part being viewed will scroll into view if necessary in the div to the left.

Here's an example lifted from developer.mozilla.org:

The para to show


<script type="text/javascript">
    function showIt(elID)
        {
            var el = document.getElementById(elID);
            el.scrollIntoView(true);
        }
</script>

<div style="height: 100px; width: 300px; overflow: scroll;">
    <div style="height: 200px"></div>
    <p id="pToShow">The para to show</p>
    <div style="height: 200px"></div>
</div>
<br>
<input type="button" value="Show para" onclick="showIt('pToShow');">


Comments
todd sharp's Gravatar Wouldn't it be safer to just use an anchor? You can link to an id with an anchor and then you wouldn't have to worry about browser support.
# Posted By todd sharp | 7/25/08 7:26 AM
Andy Matthews's Gravatar Doesn't work in IE7, just FYI. When I click the input button, all it does is to jump the page, rather than scroll it down.

Hrm...same thing for Safari on PC, and FF 2 actually. So this code doesn't work at all.
# Posted By Andy Matthews | 7/25/08 11:03 AM
Brad Wood's Gravatar @Andy: The page does jump for me depending on where it is. However, the text "The para to show" does come into view for me on IE7 and FF2.

@Todd: An anchor tag is probably a safer option, but you would have to have an ancher there to be able to go to it. This method lets you choose if the element scrolls to the top of the screen or the bottom and essesntially makes ANY element in the page available to scroll into view. I just wanted to point a method not many people know about.
# Posted By Brad Wood | 7/25/08 12:46 PM
BlogCFC (5.9.004) by Ray Camden. Blog Owner: Brad Wood