1

How can I get an editable div to remember the position of the scroll bar? Im currently programming a Chrome extension and have a notepad style editable div which users can write notes in. I have the code listed below currently which autofocuses the div onload and displays the caret at the end of the text within the div.

I now just need my scroll bar to scroll level with the caret if its further down the div.

    var div = document.getElementById("edit_notepad");

div.onfocus = function() {
    window.setTimeout(function() {
        var sel, range;
        if (window.getSelection && document.createRange) {
            range = document.createRange();
            range.selectNodeContents(div);
            range.collapse(false);
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.body.createTextRange) {
            range = document.body.createTextRange();
            range.moveToElementText(div);
            range.collapse(false);
            range.select();
        }
    }, 1);
};

div.focus();
Alex
  • 376
  • 1
  • 17

2 Answers2

2

You may want to try the different approaches done in Scroll to bottom of Div on page load (jQuery) and choose which best suits your concern.

One suggested solution is to scroll down to the height of the div as suggested by @Mike Todd

Correct version:

$('#div1').scrollTop($('#div1')[0].scrollHeight);

This related SO post might also help.

Community
  • 1
  • 1
Teyam
  • 7,686
  • 3
  • 15
  • 22
0

Why don't you try some simple localStorage?

var position = localStorage.position || 0;
div.scrollTop = position;
localStorage.setItem("position", div.scrollTop);

The code above should get and set the position of the div scroll amount, as far as I know.

Caleb Mayhew
  • 58
  • 11