Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 911
Imran Naqvi Avatar asked Feb 21 '12 12:02

Imran Naqvi


1 Answers

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>
like image 92
hamish Avatar answered Oct 01 '22 13:10

hamish