how to reset scroll position in a div using javascript

73,974

Solution 1

Finally this worked for me

function resetScrollPos(selector) {
  var divs = document.querySelectorAll(selector);
  for (var p = 0; p < divs.length; p++) {
    if (Boolean(divs[p].style.transform)) { //for IE(10) and firefox
      divs[p].style.transform = 'translate3d(0px, 0px, 0px)';
    } else { //for chrome and safari
      divs[p].style['-webkit-transform'] = 'translate3d(0px, 0px, 0px)';
    }
  }
}
resetScrollPos('.mblScrollableViewContainer');

Calling this function after transition between view ,will reset my scroll position.

Solution 2

Without seeing code, i can just guess. If you want to reset the scroll position you can simply use

window.scrollTo(0,0); 

add this code to your each tab click functions so that when ever you click any tab, it resets to top.

If you have any specific div that has overflow property

var myDiv = document.getElementById('specificDiv');
myDiv.scrollTop = 0;

Solution 3

It is easy

 <div id="test" style="height:150px; width:600px;overflow-y:auto;background-color:gray;">
     <div style="width:150px;height:500px; background-color:green;"></div>
 </div>
document.getElementById('test').scrollTop =0;
Share:
73,974
Anand Jha
Author by

Anand Jha

Hello guys, I am a Senior Member Technical Staff at Oracle , Bangalore

Updated on October 01, 2020

Comments

  • Anand Jha
    Anand Jha over 3 years

    I am working on a mobile hybrid application.

    In my html page, I have 3 tabs. When clicking a tab, the content of the scrollable div gets changed. My problem is when I scroll down the content of div (view) and click another tab, the content disappears (but the content is there). Please help me so I can reset the div scroll position when clicking any tab.

    Please give me suggestions only with JavaScript or CSS, not with JQuery as I am not using the JQuery library.

  • Anand Jha
    Anand Jha over 10 years
    shadow, this is not working for me, I have used this before. thanks
  • Voonic
    Voonic over 10 years
    @anand4tech can you set up a fiddle
  • Anand Jha
    Anand Jha over 10 years
    My code and logic is bit complex to show you on fiddle. if you could provide me any reference according to my requirements. Thanks
  • Dan Doyon
    Dan Doyon over 9 years
    It is not necessarily the DIV you are in but could be a UL you need to scroll
  • Timothy Ryan
    Timothy Ryan almost 6 years
    setting scrollTop DOES work, but if your div is hidden when you set it, it does not appear to work. set the scrollTop to zero AFTER you unhide it.
  • Hassan Baig
    Hassan Baig over 3 years
    Apart from the advice by @TimothyRyan above, also ensure the div you want to scrollTop has the overflow-y property. The writer of the answer also mentions this, but should have stressed it more since it is a potential pitfall