yxz122930
yxz122930

Reputation: 31

How to maintain scroll position after switching the tabs?

I am looking for a solution to maintain the scroll position after changing the "tabs".

For example, if I scroll all the way down to the page of London, then change to the Paris "page" and then go back to the London "page". I am expecting I am still at the bottom of the London "page". Fixing the tabs on the top of the pages is required and I've already done. I created a codepen: http://codepen.io/yiou/pen/rrKwKx

      <div class="frozen">
           <div id="tabrow">
               <ul class="tab">
                  <li><a href="#" class="tablinks" onclick="openCity(event, 'London')">London</a></li>
                  <li><a href="#" class="tablinks" onclick="openCity(event, 'Paris')">Paris</a></li>
                  <li><a href="#" class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</a></li>
               </ul>
           </div>
      </div>
    <div id="London" class="tabcontent">


    </div>
    <div id="Paris" class="tabcontent">


    </div>
    <div id="Tokyo" class="tabcontent">


    </div>    
  <script>
    function openCity(evt, cityName) {
        // Declare all variables
        var i, tabcontent, tablinks;

        // Get all elements with class="tabcontent" and hide them
        tabcontent = document.getElementsByClassName("tabcontent");
        for (i = 0; i < tabcontent.length; i++) {
            tabcontent[i].style.display = "none";
        }

        // Get all elements with class="tablinks" and remove the class "active"
        tablinks = document.getElementsByClassName("tablinks");
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(" active", "");
        }

        // Show the current tab, and add an "active" class to the link that opened the tab
        document.getElementById(cityName).style.display = "block";
        evt.currentTarget.className += " active";      
    };
  </script>    

I search this question on google but did not found any solution that really can work on my case. Can anyone help? Appreciate!

Upvotes: 0

Views: 3457

Answers (2)

agustin
agustin

Reputation: 2397

You're looking for the document.documentElement.scrollTop property.

When someone change the current tab get the current scroll position of the active tab an apply it to the new one. That's all.

Upvotes: 1

PLan
PLan

Reputation: 133

If you use jquery, you can use .scrollTop() to get the vertical scroll position for an element (assuming the scrollbar is tied to that element), which can be saved to a variable. Subscribe the element to the scroll event using jquery .scroll() (or the regular js onScroll event) and when it is triggered, save the value from .scrollTop() to the corresponding variable. When a tab is clicked, call .scrollTop() again with the value in the tab's scroll position variable to set the position to where it was before.

Upvotes: 1

Related Questions