29

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.

Liam
  • 22,818
  • 25
  • 93
  • 157
Derin
  • 1,965
  • 7
  • 27
  • 31

4 Answers4

25

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

location.hash = "elementId"
Liam
  • 22,818
  • 25
  • 93
  • 157
Derin
  • 1,965
  • 7
  • 27
  • 31
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
  • 17,521
  • 15
  • 59
  • 91
13

Another solution is scrollIntoView()

document.getElementById("elementID").scrollIntoView();
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
1

you can use scrollTop to scroll up.

you can use this plugin too

Vivek
  • 10,426
  • 14
  • 44
  • 65