How do I get an element to scroll into view, using jQuery?
Solution 1:
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;
Solution 2:
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
andleft
: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 });