Saving and loading a caret position in a text field via JavaScript

I am looking for a way to save and load a carriage position in a text box in a web application, so that when a user reopens a web application, they automatically return to the position they left.

I saw the jCaret plugin for jQuery, but since my web application does not use jQuery, I need something that works in pure JavaScript.

Also, what would be the best way to run the function to save the caret position? The first method that came to mind was to save it again every time you press a key, but that seems a bit inefficient. I thought that the application maintains its position through the onBeforeUnload event, but if you can think of a better way, please share!

+4
source share
2 answers

After further research, I came up with a simple solution that uses HTML5 localStorage.

Here I made a script to save the caret position:

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

And one more to download it:

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

They, combined with similar functions to set the scroll position of the screen, look great, a trick!

+2
source

With some minor changes, you can use jCaret without jQuery. I looked at the jCaret source and it uses jQuery for all two things: provide the element using jQuery selectors and check if the browser is IE. Get rid of them, and you're on your way.

More detailed instructions:

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

To use it, you need to do:

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

All Articles