30

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
  • 27,717
  • 28
  • 128
  • 190
Derin
  • 2,125
  • 7
  • 28
  • 31

4 Answers4

28

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

location.hash = "elementId"
Liam
  • 27,717
  • 28
  • 128
  • 190
Derin
  • 2,125
  • 7
  • 28
  • 31
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
1

you can use scrollTop to scroll up.

you can use this plugin too

Vivek
  • 10,978
  • 14
  • 48
  • 66