Smokey Dawson
Smokey Dawson

Reputation: 9240

Scroll to element on the page without jquery (Vanilla Javascript)

I'm aware there are many similar questions, but! They all seem to be from 2010 - 2013 and require the use of jQuery which I want to avoid.

Is there an easy way using Javascript to scroll to an element with a certain id and control where it lands?

I have tried to use scrollIntoView() but I was unable to get it to land where I wanted it. Even with the extra configuration detailed here. Is there a more precise way of doing it??

I have tried

document.getElementById('6QWsZnqyuAKke20CgG4WIQ')
  .scrollIntoView({'every different config option'});

Usually what happens is it would scroll to far or not enough, never exactly where I want it. I have also checked the browser compatibility and the options are not available in certain browsers. Is there a more precise way of doing it??

Thanks

Upvotes: 2

Views: 2267

Answers (1)

saltchicken
saltchicken

Reputation: 170

el = document.getElementById('your-el-id');
var rect = el.getBoundingClientRect();
window.scrollTo(rect.x, rect.y)

This code will position the element on top of the window. Simply modify the values in window.scrollTo() to get the desired position.

Upvotes: 3

Related Questions