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.
Say your page displays a list of names and you want a certain person to be highlighted and scrolled into view. There's a browser API for that: Element. scrollIntoView() , which scrolls an element into view.
The scrollTo method: The scrollTo() is used to scroll to the specified element in the browser. Syntax: Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. Example: Using scrollTo() to scroll to an element.
jQuery scroll() MethodThe scroll event occurs when the user scrolls in the specified element. The scroll event works for all scrollable elements and the window object (browser window). The scroll() method triggers the scroll event, or attaches a function to run when a scroll event occurs.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With