Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to a specific position on a page using Javascript / Jquery [duplicate]

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.

like image 691
Derin Avatar asked Jun 15 '11 09:06

Derin


2 Answers

After much googling I found that you just need to do this:

location.hash = "elementId" 
like image 60
Derin Avatar answered Oct 14 '22 02:10

Derin


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); 
like image 28
Josh Earl Avatar answered Oct 14 '22 04:10

Josh Earl