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:
- Download the uncompressed source for jCaret: http://examplet.buss.hk/download/download.php?plugin=caret.1.02
- Add
var caret;
to the top. - Remove the
$,
from(function($,len,createRange,duplicate){
- Remove
$.fn.
from$.fn.caret=function(options,opt2){
- Change
var start,end,t=this[0],browser=$.browser.msie;
tovar start,end,t=this[0],browser=/(msie) ([\w.]+)/.test(navigator.userAgent);
- 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!
精彩评论