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

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; offset.top -= 20;
  3. Now animate the scroll-top and scroll-left CSS properties of <body> and <html>:$('html, body').animate({ scrollTop: offset.top, scrollLeft: offset.left });

Leave a Comment