2

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

2
  • 1
    Show the code you tried, and expand on "couldn't get it to land where I wanted", does that mean it went to far, didn't go far enough, didn't do anything? Commented Mar 8, 2018 at 4:04
  • I haven't tried, but potentially you can get the distance from the top for the element that you want to scroll to, using scrollTop, and then pass it to window.scroll. Commented Mar 8, 2018 at 4:08

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

4 Comments

Im getting a linting error x and y does not exist on rect, are they meant to be numbers?
I am unsure why you would receive a linting error. Calling .x and .y will return the number for the x and y coordinates of the element's top left corner. What IDE are you using?
Im writing this in an angular application so its a tslint error sorry that says [ts] Property 'x' does not exist on type ClientRec | DOMRect I will figure out how to fix it
Ah, Typescript. That is why. The code is valid javascript and will get the job done. I believe making this proper Typescript is outside the scope of this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.