Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 515
Nasir Avatar asked Feb 03 '11 10:02

Nasir


People also ask

How do you bring an element into a view?

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.

How do I scroll to a specific div?

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.

How can use scroll event in jQuery?

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.


1 Answers

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; 
like image 78
Andy E Avatar answered Oct 07 '22 01:10

Andy E