SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Mar 2011
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Caret position in editable textarea

    The following code is the best I've been able to find for an editable HTML textarea for a WYSIWYG editor. It can save and restore the caret position. It works on FF3.5+, IE8, but does not work on Opera 11, Safari 5, or Chrome 10. Any ideas why? I'm just trying to find some code that works on FF3+, opera 10+, safari 5, chrome 8+, and IE7+.

    Code:
    function doGetCaretPosition(ctrl) {
    	var CaretPos = 0;	// IE Support
    	if (document.selection) {
    		ctrl.focus ();
    		var Sel = document.selection.createRange();
    		Sel.moveStart ('character', -ctrl.value.length);
    		CaretPos = Sel.text.length;
    	}else if (ctrl.selectionStart || ctrl.selectionStart == '0'){
    		// Firefox support
    		CaretPos = ctrl.selectionStart;
    	}
    	return (CaretPos);
    }
    function setCaretPosition(ctrl, pos){
    	if(ctrl.setSelectionRange){
    		ctrl.focus();
    		ctrl.setSelectionRange(pos,pos);
    	}else if (ctrl.createTextRange) {
    		var range = ctrl.createTextRange();
    		range.collapse(true);
    		range.moveEnd('character', pos);
    		range.moveStart('character', pos);
    		range.select();
    	}
    }
    
    cpos=doGetCaretPosition(document.getElementById('yourtextareaID'));
    
    setCaretPosition(document.getElementById('yourtextareaID'),cpos);

  2. #2
    SitePoint Member Peralta's Avatar
    Join Date
    Mar 2011
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    jQuery has some great plugins for caret positioning. I've used a couple, but cannot recall which ones.

  3. #3
    SitePoint Member
    Join Date
    Mar 2011
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'll look into jQuery. BTW I'm using designmode.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •