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 4.1k times
29
4 Answers
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);
![](../../users/profiles/532797.webp)
Josh Earl
- 17,521
- 15
- 59
- 91
-
-
-
2@nwillo `window.scrollTo({ top: positionY, left: positionX, behavior: 'smooth' });` – jami0821 Oct 24 '19 at 17:25
13
Another solution is scrollIntoView()
document.getElementById("elementID").scrollIntoView();
![](../../users/profiles/2236241.webp)
Prabowo Murti
- 1,146
- 1
- 18
- 23
-
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