How to go to a specific element on page?
document.getElementById("elementID").scrollIntoView();
Same thing, but wrapping it in a function:
function scrollIntoView(eleID) {
var e = document.getElementById(eleID);
if (!!e && e.scrollIntoView) {
e.scrollIntoView();
}
}
This even works in an IFrame on an iPhone.
Example of using getElementById: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_document_getelementbyid
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 );
The standard technique in plugin form would look something like this:
(function($) {
$.fn.goTo = function() {
$('html, body').animate({
scrollTop: $(this).offset().top + 'px'
}, 'fast');
return this; // for chaining...
}
})(jQuery);
Then you could just say $('#div_element2').goTo();
to scroll to <div id="div_element2">
. Options handling and configurability is left as an exercise for the reader.