How do I get an element to scroll into view, using jQuery?

There’s a DOM method called scrollIntoView, which is supported by all major browsers, that will align an element with the top/left of the viewport (or as close as possible).

$("#myImage")[0].scrollIntoView();

On supported browsers, you can provide options:

$("#myImage")[0].scrollIntoView({
    behavior: "smooth", // or "auto" or "instant"
    block: "start" // or "end"
});

Alternatively, if all the elements have unique IDs, you can just change the hash property of the location object for back/forward button support:

$(document).delegate("img", function (e) {
    if (e.target.id)
        window.location.hash = e.target.id;
});

After that, just adjust the scrollTop/scrollLeft properties by -20:

document.body.scrollLeft -= 20;
document.body.scrollTop -= 20;

Leave a Comment