JavaScript method of the day: scrollIntoView()

JavaScript method of the day: scrollIntoView()

Posted by Brad Wood
Jul 25, 2008 09:48:00 UTC
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


[code]<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');">


[/code]

 


todd sharp

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.

Andy Matthews

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.

Brad Wood

@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.

Dragos Stancu

Hi guys,

Just posted some workaround using jQuery: http://www.webfixtech.com/blog/2009/03/jquery-scrollintoview-in-one-line/

Toby Teel

Those two guys are crazy. Works in FF 3.5 and IE 7 and Chrome 3 (so probably Safari as well.)

I'd love to see some code to only scroll into view if it isn't already visible. Otherwise, like an anchor, the screen jumps even if the element is already in view.

Mike

Try changing the onclick code to: onclick="showIt('pToShow');return false"

That gets it to work for me. Otherwise it flicks to the found text before immediately jumping back to the top of the page.

Site Updates

Entry Comments

Entries Search