jQuery move Cursor Back "X" amount of Spaces
Asked Answered
F

1

2

I need it so that when a button is pressed, the cursor will:

1) Locate the end of the sentence 2) Move the cursor back from the end of the sentence "x" many spaces (x is a variable);

Here's a fiddle -----> jsFiddle <------

HTML

<span>From the end, move the cursor back this many spaces: </span>
<input type='text'   id='num' size='5'/>
<button>Submit</button>
<br/><br/>
<textarea>The cursor will move in here</textarea>

jQuery

$(document).ready(function() {
  $('button').click(function() {
   var myval = parseInt($('#num').val()); //the number of spaces to move back
    //code to move cursor back - starting from the END OF THE STATEMENT
  });
});
Felonious answered 14/7, 2013 at 3:2 Comment(1)
Have you seen this: #513028Skidmore
M
3

You'd do that like so :

$(document).ready(function() {
    $('button').click(function() {
        var el      = $('textarea')[0],
            myval   = parseInt($('#num').val(), 10),
            cur_pos = 0;

        if (el.selectionStart) { 
            cur_pos = el.selectionStart; 
        } else if (document.selection) { 
            el.focus(); 

            var r = document.selection.createRange(); 
            if (r != null) {
                var re = el.createTextRange(), 
                    rc = re.duplicate(); 
                re.moveToBookmark(r.getBookmark()); 
                rc.setEndPoint('EndToStart', re); 

                cur_pos = rc.text.length; 
            }
        }  

        if (el.setSelectionRange) {
            el.focus();
            el.setSelectionRange(cur_pos-myval, cur_pos-myval);
        }
          else if (el.createTextRange) {
            var range = el.createTextRange();
            range.collapse(true);
            range.moveEnd('character', cur_pos-myval);
            range.moveStart('character', cur_pos-myval);
            range.select();
        }
    });
});

FIDDLE

Moonier answered 14/7, 2013 at 3:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.