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
Related
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.
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
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
I have a textarea and I'm trying to check if someone enters {{link that I can have a modal pop up to let them complete some information.
What I have now is that if someone enters the letter k, it will go back 6 characters and then determine if the text matches {{link
But I'm having a problem in setting setting the start and end points for the range. I think that the problem is with identifying the node, but I'm not sure.
Mainly when someone enters a the letter "k", I'm just trying to go back to check if they had typed: {{link and if they did, it would launch a modal.
This is what I have that isn't working at the part where I'm trying to set the range and get the selection.
$(document).on('keyup', 'textarea', function(e) {
if (e.keyCode == 75) {
var end = $('textarea').getCaretPosition();
var start = end - 6;
var node = $(this).get(0);
var range = document.createRange();
range.setStart(node, start);
range.setEnd(node, end);
var selection = range.toString();
if( selection == '{{link' ){
// we'll launch a modal here
}
}
});
$.fn.getCaretPosition = 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;
}
This generates the error: Uncaught Error: INDEX_SIZE_ERR: DOM Exception 1 at range.setStart(node, start);
Not sure if this is what you mean http://jsfiddle.net/sailorob/J6PVJ/
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>