how to remember scroll position of page

前端 未结 7 1739
南笙
南笙 2020-12-15 00:31

I am submitting some data to my database then reloading the same page as the user was just on, I was wondering if there is a way to remember the scroll position the user was

相关标签:
7条回答
  • 2020-12-15 01:16

    Well, if you use _targets in your code you can save that.

    Or, you can do an ajax request to get the window.height.

     document.body.offsetHeight;
    

    Then drop them back, give the variable to javascript and move the page for them.

    0 讨论(0)
  • 2020-12-15 01:17

    I had major problems with cookie javascript libraries, most cookie libraries could not load fast enough before i needed to scroll in the onload event. so I went for the modern html5 browser way of handling this. it stores the last scroll position in the client web browser itself, and then on reload of the page reads the setting from the browser back to the last scroll position.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    
    <script type="text/javascript">
    $(document).ready(function () {
    
        if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
            $(window).scrollTop(localStorage.getItem("my_app_name_here-quote-scroll"));
        }
    
        $(window).on("scroll", function() {
            localStorage.setItem("my_app_name_here-quote-scroll", $(window).scrollTop());
        });
    
      });
    </script>
    
    0 讨论(0)
  • 2020-12-15 01:18

    To Remember Scroll all pages Use this code

    $(document).ready(function (e) {
        let UrlsObj = localStorage.getItem('rememberScroll');
        let ParseUrlsObj = JSON.parse(UrlsObj);
        let windowUrl = window.location.href;
    
        if (ParseUrlsObj == null) {
            return false;
        }
    
        ParseUrlsObj.forEach(function (el) {
            if (el.url === windowUrl) {
                let getPos = el.scroll;
                $(window).scrollTop(getPos);
            }
        });
    
    });
    
    function RememberScrollPage(scrollPos) {
    
        let UrlsObj = localStorage.getItem('rememberScroll');
        let urlsArr = JSON.parse(UrlsObj);
    
        if (urlsArr == null) {
            urlsArr = [];
        }
    
        if (urlsArr.length == 0) {
            urlsArr = [];
        }
    
        let urlWindow = window.location.href;
        let urlScroll = scrollPos;
        let urlObj = {url: urlWindow, scroll: scrollPos};
        let matchedUrl = false;
        let matchedIndex = 0;
    
        if (urlsArr.length != 0) {
            urlsArr.forEach(function (el, index) {
    
                if (el.url === urlWindow) {
                    matchedUrl = true;
                    matchedIndex = index;
                }
    
            });
    
            if (matchedUrl === true) {
                urlsArr[matchedIndex].scroll = urlScroll;
            } else {
                urlsArr.push(urlObj);
            }
    
    
        } else {
            urlsArr.push(urlObj);
        }
    
        localStorage.setItem('rememberScroll', JSON.stringify(urlsArr));
    
    }
    
    $(window).scroll(function (event) {
        let topScroll = $(window).scrollTop();
        console.log('Scrolling', topScroll);
        RememberScrollPage(topScroll);
    });
    
    0 讨论(0)
  • 2020-12-15 01:19

    Store the position in an hidden field.

    <form id="myform">
      <!--Bunch of inputs-->
    </form>
    

    than with jQuery store the scrollTop and scrollLeft

    $("form#myform").submit(function(){
       $(this).append("<input type='hidden' name='scrollTop' value='"+$(document).scrollTop()+"'>");
    
       $(this).append("<input type='hidden' name='scrollLeft' value='"+$(document).scrollLeft()+"'>");
    });
    

    Than on next reload do a redirect or print them with PHP

    $(document).ready(function(){
       <?php
          if(isset($_REQUEST["scrollTop"]) && isset($_REQUEST["scrollLeft"]))
             echo "window.scrollTo(".$_REQUEST["scrollTop"].",".$_REQUEST["scrollLeft"].")";
       ?>
    });
    
    0 讨论(0)
  • 2020-12-15 01:25

    I tackle this via using window.pageYOffset . I saved value using event listener or you can directly call window.pageYOffset. In my case I required listener so it is something like this:

    window.addEventListener('scroll', function() {
      document.getElementById('showScroll').innerHTML = window.pageYOffset + 'px';
    })
    
    

    And I save latest scroll position in localstorage. So when next time user comes I just check if any scroll value available via localstorage if yes then scroll via window.scrollTo(0,myScrollPos)

    0 讨论(0)
  • 2020-12-15 01:27

    (1) Solution 1:

    First, get the scroll position by JavaScript when clicking the submit button.

    Second, include this scroll position value in the data submitted to PHP page.

    Third, PHP code should write back this value into generated HTML as a JS variable:

    <script>
    var Scroll_Pos = <?php echo $Scroll_Pos; ?>;
    </script>
    

    Fourth, use JS to scroll to position specified by the JS variable 'Scroll_Pos'

    (2) Solution 2:

    Save the position in cookie, then use JS to scroll to the saved position when page reloaded.

    0 讨论(0)
提交回复
热议问题