How to go to a specific element on page?

Cuga picture Cuga · Jan 26, 2011 · Viewed 276k times · Source

On my HTML page, I want to be able to 'go to' / 'scroll to' / 'focus on' an element on the page.

Normally, I'd use an anchor tag with a href="#something", but I'm already using the hashchange event along with the BBQ plugin to load this page.

So is there any other way, via JavaScript, to have the page go to a given element on the page?

Here's the basic outline of what I'm trying to do:

function focusOnElement(element_id) {
     $('#div_' + element_id).goTo(); // need to 'go to' this element
}

<div id="div_element1">
   yadda yadda 
</div>
<div id="div_element2">
   blah blah
</div>

<span onclick="focusOnElement('element1');">Click here to go to element 1</span>
<span onclick="focusOnElement('element2');">Click here to go to element 2</span>

Answer

user113716 picture user113716 · Jan 26, 2011

If the element is currently not visible on the page, you can use the native scrollIntoView() method.

$('#div_' + element_id)[0].scrollIntoView( true );

Where true means align to the top of the page, and false is align to bottom.

Otherwise, there's a scrollTo() plugin for jQuery you can use.

Or maybe just get the top position()(docs) of the element, and set the scrollTop()(docs) to that position:

var top = $('#div_' + element_id).position().top;
$(window).scrollTop( top );