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

javascript, jquery

Solution

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:

Get the image offsets (relative to the document):

var offset = $(this).offset(); // Contains .top and .left

Subtract 20 from `top` and `left`:

offset.left -= 20;
offset.top -= 20;

Now animate the scroll-top and scroll-left CSS properties of `<body>` and `<html>`:

$('html, body').animate({
    scrollTop: offset.top,
    scrollLeft: offset.left
});

Problem

I have an HTML document with images in a grid format using `<ul><li><img...`. The browser window has both vertical & horizontal scrolling. Question: When I click on an image `<img>`, 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.

Original source

Related problems