It is possible to move to a certain position on a page using #elementId
. How can I do the same thing using Javascript / Jquery. When a JS function is called, I want to scroll to the specific position on that page.
Asked
Active
Viewed 5.4k times
30
4 Answers
17
Another solution is scrollIntoView()
document.getElementById("elementID").scrollIntoView();

Prabowo Murti
- 1,216
- 2
- 18
- 27
-
when *behavior:smooth* will be available , this will be the perfect solution (as right now it just jumps - which is not ideal UX) – Claudiu Aug 07 '17 at 08:11
14
Here's an example function that I tested on today's New York Times front page using the browser console:
function scrollToElement(pageElement) {
var positionX = 0,
positionY = 0;
while(pageElement != null){
positionX += pageElement.offsetLeft;
positionY += pageElement.offsetTop;
pageElement = pageElement.offsetParent;
window.scrollTo(positionX, positionY);
}
}
var pageElement = document.getElementById("insideNYTimesHeader");
scrollToElement(pageElement);

Josh Earl
- 18,151
- 15
- 62
- 91
-
-
-
2@nwillo `window.scrollTo({ top: positionY, left: positionX, behavior: 'smooth' });` – jami0821 Oct 24 '19 at 17:25