Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML/Javascript: remember scroll independent of the window size

I've got a webpage for reading books online. I'd like to save the position inside the document so when a user resumes his reading, he starts in the point where he previously was.

I can get the scroll using things like window.pageYOffset, but this depends on the browser window size. In other words, if you make your window narrower, the same text will be at a different scroll (see the image for an example).

So I need to come up with a window-size independent way of measuring scroll. Any ideas?

Note: I only need this to work on mozilla based browsers.

Problem example

Thanks in advance

like image 506
user683887 Avatar asked Sep 19 '11 20:09

user683887


Video Answer


2 Answers

Aaaaaaand my version is late... again... but at least I have a demo:

My method also uses percents (scroll position / (scroll height - container height))

http://jsfiddle.net/wJhFV/show

$(document).ready(function(){
    var container = $("#container")[0];
    container.scrollTop =
        Number(localStorage["currentPosition"]) *
        (container.scrollHeight - $(container).height())

})

$("#container").scroll(function(){
    console.log("set to: ")
        console.log(
        localStorage["currentPosition"] =
            (this.scrollTop) /
            (this.scrollHeight - $(this).height())
        );
})
like image 90
Joseph Marikle Avatar answered Oct 17 '22 06:10

Joseph Marikle


If my assumption is right that the relative scrollTop value in relation to the document height is always the same, the problem could be solved rather simply.

First set a cookie with the read percentage:

var read_percentage = document.body.scrollTop / document.body.offsetHeight;
document.cookie = 'read_percentage=' + read_percentage + '; expires=Thu, 2 Aug 2021 20:47:11 UTC; path=/'

On the next page load you can restore the position by setting the scrollTop value on the body:

var read_percentage = read_cookie('read_percentage');
document.body.scrollTop = document.body.offsetHeight * read_percentage

Note that read_cookie is not a browser function. You have to implement it. Example can be found on http://www.quirksmode.org/js/cookies.html

I tested this on a large page and it worked quite fine.

like image 1
topek Avatar answered Oct 17 '22 08:10

topek