Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript scrollIntoView() middle alignment?

Javascript .scrollIntoView(boolean) provide only two alignment option.

  1. top
  2. bottom

What if I want to scroll the view such that. I want to bring particular element somewhere in middle of the page?

like image 209
Dhruv Bansal Avatar asked Jan 19 '12 06:01

Dhruv Bansal


People also ask

How do I make my scrollIntoView smooth?

To use JavaScript scrollIntoView to do smooth scroll with offset, we can call scrollTo with an object that has the top and behavior properties. const element = document. getElementById("targetElement"); const headerOffset = 45; const elementPosition = element. getBoundingClientRect().

Does scrollIntoView work horizontally?

scrollIntoView(true);", element); This works for vertical scrolling but not for horizontal.

What is JavaScript scrollIntoView?

The scrollIntoView() method scrolls an element into the visible area of the browser window.

How do I get the element in view 1 pick option?

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.


2 Answers

try this :

 document.getElementById('myID').scrollIntoView({             behavior: 'auto',             block: 'center',             inline: 'center'         }); 

refer here for more information and options : https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

like image 59
hakuna Avatar answered Sep 20 '22 10:09

hakuna


It is possible to use getBoundingClientRect() to get all the information you need to achieve this. For example, you could do something like this:

const element = document.getElementById('middle'); const elementRect = element.getBoundingClientRect(); const absoluteElementTop = elementRect.top + window.pageYOffset; const middle = absoluteElementTop - (window.innerHeight / 2); window.scrollTo(0, middle); 

Demo: http://jsfiddle.net/cxe73c22/

This solution is more efficient than walking up parent chain, as in the accepted answer, and doesn't involve polluting the global scope by extending prototype (generally considered bad practice in javascript).

The getBoundingClientRect() method is supported in all modern browser.

like image 39
Rohan Orton Avatar answered Sep 18 '22 10:09

Rohan Orton