Nasir Nasir - 1 month ago 5x
jQuery Question

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

I have an HTML document with images in a grid format using

. The browser window has both vertical & horizontal scrolling.

When I click on an image
, how then do I get the whole document to scroll to a position where the image I just clicked on is
top:20px; left:20px

I've had a browse on here for similar posts...although I'm quite new to JavaScript, and want to understand how this is achieved for myself.

Any help would be greatly appreciated. Thanks.


Since you want to know how it works, I'll explain it step-by-step.

First you want to bind a function as the image's click handler:

$('#someImage').click(function () {
    // Code to do scrolling happens here

That will apply the click handler to an image with id="someImage". If you want to do this to all images, replace '#someImage' with 'img'.

Now for the actual scrolling code:

  1. Get the image offsets (relative to the document):

    var offset = $(this).offset(); // Contains .top and .left
  2. Subtract 20 from top and left:

    offset.left -= 20; -= 20;
  3. Now animate the scroll-top and scroll-left CSS properties of <body> and <html>:

    $('html, body').animate({
        scrollLeft: offset.left