简体   繁体   中英

Saving and loading the caret position in a textarea via JavaScript

I'm looking for a method to save and load the caret position in a textarea in a web-application, so that when the user re-opens the web-application they are automatically taken back to the position they left it.

I've seen the jCaret plugin for jQuery, but as my web application does not use jQuery I need something that works in pure JavaScript.

Also, what would be the best way of initiating the function to save the caret's position? The first method that came to mind was re-saving it on every keypress, but this seems a little inefficient. I've been thinking of having the application save the position via the onBeforeUnload event, but if you can think of a better way please share!

With some minor modifications, you can use jCaret without jQuery. I had a look at the jCaret source, and it uses jQuery for all of two things: to supply the element using jQuery selectors, and to test if the browser is IE. Get rid of these and you're on your way.

More detailed instructions:

  1. Download the uncompressed source for jCaret: http://examplet.buss.hk/download/download.php?plugin=caret.1.02
  2. Add var caret; to the top.
  3. Remove the $, from (function($,len,createRange,duplicate){
  4. Remove $.fn. from $.fn.caret=function(options,opt2){
  5. Change var start,end,t=this[0],browser=$.browser.msie; to var start,end,t=this[0],browser=/(msie) ([\\w.]+)/.test(navigator.userAgent);
  6. In the very last line, remove jQuery, from })(jQuery,"length","createRange","duplicate");

To use it, you need to do:

caret.call([document.getElementById("myText")], options, opt2);

After further research, I've come to a simple solution that uses HTML5 localStorage.

Here's the script I made for saving the caret position:

function caretPositionSave() { 
    window.localStorage.setItem("CaretPosition", document.querySelector("#editor").selectionStart);
};

And another one for loading it:

function caretPositionLoad() {
    document.querySelector("#editor").focus();
    if (localStorage.CaretPosition) {
        document.querySelector("#editor").selectionStart = localStorage.CaretPosition;
    };
};

These, combined with similar functions to set the screen's scroll position, seem to do the trick perfectly!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM