9

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

user683887
  • 1,260
  • 1
  • 10
  • 20
  • +1, best question I've seen all day! – Brad Sep 19 '11 at 20:55
  • I don't see much difference in the positions. What's the maximum deviance you've seen? – Joseph Marikle Sep 19 '11 at 20:59
  • 2
    See also: http://stackoverflow.com/questions/7331701/how-to-know-what-lines-chars-are-currently-visible-in-a-textarea If you could figure that out, upon next load you can drop in an anchor or other element and do a scrollTo. – Brad Sep 19 '11 at 21:00
  • @Joseph it's not a real example, just to notice how the scroll bar changes. In a real world one, for the same paragraph: full window size -> scroll 260, 50% size -> scroll 1380. brad: going to take a look. – user683887 Sep 19 '11 at 21:05

2 Answers2

2

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())
        );
})
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
1

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.

topek
  • 18,609
  • 3
  • 35
  • 43