How to remember scroll position and scroll back
Asked Answered
O

5

14

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?
Ordonez answered 21/2, 2012 at 12:53 Comment(2)
Answer for number 2 is window.scrollTo(x,y)Petry
For a great explanation and code on different methods for finding the scroll position, please refer to http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.htmlConcenter
B
11

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>
Burnette answered 1/9, 2019 at 16:35 Comment(0)
B
3

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.

Battled answered 16/1, 2021 at 3:11 Comment(0)
G
2
  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">
Garmaise answered 12/7, 2018 at 21:49 Comment(0)
T
1

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);
});
Tense answered 30/7, 2019 at 10:58 Comment(0)
O
1

Yet another way without any libraries and with smooth scrolling as the cherry.

const path = window.location.pathname;
const list = path.split('/');
const cookieName = list.filter(n => n).pop();

window.addEventListener('load', function () {
  const position = getCookie(cookieName);

  if (position !== undefined) {
    setTimeout(function () {
      console.log(`restore scroll position - ${position}`);
      window.scrollTo({
        top: position,
        left: 0,
        behavior: 'smooth',
      });
    }, 1);
  }
});

let timerId;

window.addEventListener('scroll', function () {
  if (timerId) {
    clearTimeout(timerId);
  }

  timerId = setTimeout(function () {
    const position = window.pageYOffset;
    console.log(`set scroll cookie - ${position}`);
    setCookie(cookieName, position, {secure: true, 'max-age': 'session'});
  }, 300);
});

NOTE: The getCookie and setCookie can be found here https://javascript.info/cookie

Orcein answered 12/12, 2023 at 6:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.