简体   繁体   中英

How to remember scroll position and scroll back

I am using html2canvas library and when I call html2canvas.Parse() the page scroll to top.

I thought if i can remember the position before calling html2canvas.Parse(), so then i can go back to original scroll position.

  1. get the current position of browser scroll (specially vertical)?
  2. scroll back to position which i stored earlier?

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>
  1. Save scroll position to a variable
  2. Do something
  3. Scroll Back

I'm using jQuery in the example below to make things easy but you could easily do the same thing in vanilla js.

 var scrollPos; $('.button').on('click', function() { // save scroll position to a variable scrollPos = $(window).scrollTop(); // do something $('html, body').animate({ scrollTop: $("#cats").offset().top }, 500); // scroll back setTimeout( function() { $('html, body').animate({ scrollTop: scrollPos }, 500); }, 1000); });
 .button { position: fixed; font-size: 12px; margin: 10px; } #rainbow { height: 2000px; background: -webkit-linear-gradient(red, orange, yellow, green, cyan, blue, violet); background: -o-linear-gradient(red, orange, yellow, green, cyan, blue, violet); background: -moz-linear-gradient(red, orange, yellow, green, cyan, blue, violet); background: linear-gradient(red, orange, yellow, green, cyan, blue, violet); } #cats { width: 100%; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> <input class="button" value="Scroll down a bit then click here for 1 second of cats!" type="button"> <div id="rainbow"></div> <img id="cats" title="By Alvesgaspar [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0 )], via Wikimedia Commons" width="1024" alt="Cat poster 1" src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Cat_poster_1.jpg/1024px-Cat_poster_1.jpg">

To Remember Scroll 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);
});

This worked for me:

window.onbeforeunload = function () {
        var scrollPos;
        if (typeof window.pageYOffset != 'undefined') {
            scrollPos = window.pageYOffset;
        }
        else if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') {
            scrollPos = document.documentElement.scrollTop;
        }
        else if (typeof document.body != 'undefined') {
            scrollPos = document.body.scrollTop;
        }
        document.cookie = "scrollTop=" + scrollPos + "URL=" + window.location.href;
    }

window.onload = function () {
    if (document.cookie.includes(window.location.href)) {
        if (document.cookie.match(/scrollTop=([^;]+)(;|$)/) != null) {
            var arr = document.cookie.match(/scrollTop=([^;]+)(;|$)/);
            document.documentElement.scrollTop = parseInt(arr[1]);
            document.body.scrollTop = parseInt(arr[1]);
        }
    }
}

Most of this code I found elsewhere, unfortunately I cannot find the source anymore. Just added a check to see if the URL is the same so that the scroll position is only saved for the same page, not for other pages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM