Get cursor position in Textbox using JQuery - javascript

I wanted to get current cursor position in a textbox using JQuery. Cursor position may change using keyboard arrow keys, while typing or mouse press. Is there a way to get this done.
var currentCursorPosition = $("#textbox").currentCursorPosition();

With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
source: Caret position in textarea, in characters from the start

Fiddle: This solves my problem.
<textarea id="textarea" style="width:80%;height:100px;"></textarea><br/>
<input type="text" id="indicator" style="width:30px;">
JavaScript:
var indicator = document.getElementById("indicator");
var textarea = document.getElementById("textarea");
setInterval(function() { indicator.value = caret(textarea);}, 100);
function caret(node) {
if(node.selectionStart) return node.selectionStart;
else if(!document.selection) return 0;
//node.focus();
var c= "\001";
var sel= document.selection.createRange();
var txt= sel.text;
var dul= sel.duplicate();
var len= 0;
try{
dul.moveToElementText(node);
}
catch(e){
return 0;
}
sel.text= txt + c;
len= (dul.text.indexOf(c));
sel.moveStart('character',-1);
sel.text= "";
return len;
}
Source: Source page

Related

How I can keep the cursor in its position in textarea after auto-submitting?

I have a form and textarea, I do auto submit for form after x seconds ... But every time auto submit is done the cursor jumps out of textarea ...
so how can I keep the cursor after submitting in old position in texrarea ?
In your auto submit code get the current position of the cursor in the textarea. You can do it with this function (where id is the id attribute of the textarea element):
function getCaretPosition(id) {
var txt = document.getElementById(id);
var startPos = txt.selectionStart;
var endPos = txt.selectionEnd;
return endPos;
}
Than store the the value somewhere (in localstorage for instance), and after the form submit restore the cursor position with this function:
function setCaretPosition(id) {
var txt = document.getElementById(id);
if(txt.createTextRange) {
var range = txt.createTextRange();
range.collapse(true);
range.moveEnd('character', caretPos);
range.moveStart('character', caretPos);
range.select();
return;
}
if(txt.selectionStart) {
txt.focus();
txt.setSelectionRange(caretPos, caretPos);
}
}
where the caretPos is the cursor position stored before the submit. Here is simple demo to see how the functions work https://jsfiddle.net/p0oc8tjs/2/
Use the autofocus textarea attribute. Example:
<textarea autofocus></textarea>
This Boolean attribute lets you specify that a form control should
have input focus when the page loads, unless the user overrides it,
for example by typing in a different control. Only one form-associated
element in a document can have this attribute specified.
If you still want to use script and set the last cursor position, than using sessionStorage you can do:
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
} else if('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
};
$.fn.selectRange = function(start, end) {
if(end === undefined) {
end = start;
};
return this.each(function() {
if('selectionStart' in this) {
this.selectionStart = start;
this.selectionEnd = end;
} else if(this.setSelectionRange) {
this.setSelectionRange(start, end);
} else if(this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
var textarea = $('.remember-cursor');
textarea.on('input click keyup', function(e) {
sessionStorage.cursorPosition = textarea.getCursorPosition();
});
$(document).on('ready', function(e) {
textarea.focus().selectRange( sessionStorage.cursorPosition );
});
$('button').on('click', function(e) {
$(document).trigger('ready');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="remember-cursor">adsfsadfsad</textarea>
<button>Trigger DOM ready</button>
Thanks to this posts and answers:
Cursor position in a textarea
jQuery Set Cursor Position in Text Area
Also on JSFiddle.
Still, I do not think this is a correct way to do it. You should post your data via AJAX and collect results.

Caret position in textarea and surrounding characters

What I need is this. I need a function that gets position of cursor in textarea and check if surrounding characters are "<" and ">" (without ""). I have a function that gets caret position
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
So this is example:
<textarea>
<paragraph>Text goes here.</paragraph>
<picture>Picture</picture>*(* is caret)
</textarea>
function xyz(){
var i=getCaret(textarea);
var previous_character=textarea.value(i-1);
var next_character=textarea.value(i+1);
if(previous_character==some_character and next_character==some_character){
do something...
}
}
You can get the the characters using String objects charAt function (character at)
var previous_character=textarea.value.charAt(i-1);
var next_character=textarea.value.charAt(i); // i will give you the next

get the line number with string("Line no.") from textarea?

I have used a code that show the line number from textarea and it works with me.But i would like to show a string beside that so the output will be:
Line number: 3
here is the code that I have used:
http://jsfiddle.net/S2yn3/1/
and the function is:
$(function() {
$('#test').keyup(function() {
var pos = 0;
if (this.selectionStart)
pos = this.selectionStart;
} else if (document.selection) {
this.focus();
var r = document.selection.createRange();
if (r == null) {
pos = 0;
} else {
var re = this.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
pos = rc.text.length;
}
}
$('#c').html(this.value.substr(0, pos).split("\n").length);
});
});
Thanks guys
Your code is counting the number of '\n' characters from the first character to the cursor. If you're looking for the total number of linebreaks, change...
$('#c').html(this.value.substr(0, pos).split("\n").length);
to
$('#c').html('Line no. ' + this.value.split("\n").length);

HTML form, make tab key trigger indent?

The default behaviour in browsers is to select the next form element. I want my textbox to indent code by, lets say 4 spaces when tab is pressed. Just like if you were indenting code in an IDE. How would I achieve this behaviour in JavaScript? If I have to use jQuery, or its easier, I'm fine with that.
Thanks!
Tracking the key code and adding 4 spaces to the element should do it. You can prevent the default when the tab key is pressed. Like so?:
Edit after all comments:
Ahh, ok so you're actually asking for several JS functions (get cursor position in text area, change text, set cursor position in text area). A little more looking around would have given you all of these, but since I'm a nice guy I'll put it in there for ya. The other answers can be found in this post about getCursorPosition() and this post about setCursorPosition(). I updated the jsFiddle for ya. Here's the code update
<script>
$('#myarea').on('keydown', function(e) {
var thecode = e.keyCode || e.which;
if (thecode == 9) {
e.preventDefault();
var html = $('#myarea').val();
var pos = $('#myarea').getCursorPosition(); // get cursor position
var prepend = html.substring(0,pos);
var append = html.replace(prepend,'');
var newVal = prepend+' '+append;
$('#myarea').val(newVal);
$('#myarea').setCursorPosition(pos+4);
}
});
new function($) {
$.fn.getCursorPosition = function() {
var pos = 0;
var el = $(this).get(0);
// IE Support
if (document.selection) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
// Firefox support
else if (el.selectionStart || el.selectionStart == '0')
pos = el.selectionStart;
return pos;
}
} (jQuery);
new function($) {
$.fn.setCursorPosition = function(pos) {
if ($(this).get(0).setSelectionRange) {
$(this).get(0).setSelectionRange(pos, pos);
} else if ($(this).get(0).createTextRange) {
var range = $(this).get(0).createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
}(jQuery);
​
</script>
<textarea id="myarea"></textarea>

Get coordinates of event in textBox or TextArea?

If I listen to the text box (textarea) key-down event, can I get the coordinates of event when user type any characters into it?
$('#textAreaId').bind('keydown', function(event) {
var data = event.originalEvent.touches ? event.originalEvent.touches[0] : event;
alert(data.pageY);
});
Do you want the position of the element or the position of the caret?
To get the position of the caret you can use the following function (borrowed from another question):
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
To get the position of the textarea element relative to the document, you use .offset:
$("#textAreaId").bind('keydown', function(event){
var offset = $(this).offset();
console.log(offset);
});
I put up a test case on jsFiddle.
Caret position in textarea, in characters from the start

Categories