The script below inserts text to the end of text area. I need to change to insert text after current cursor position in the text area.
jQuery(document).ready(function($){
$('#addCommentImage').click(function(){
var imageLoc = prompt('Enter the Image URL:');
if ( imageLoc ) {
$('#comment').val($('#comment').val() + '[img]' + imageLoc + '[/img]');
}
return false;
});
});
To add text to a textarea, access the value property on the element and set it to its current value plus the text to be appended, e.g. textarea. value += 'Appended text' . The value property can be used to get and set the content of a textarea element.
In computer user interfaces, a cursor is an indicator used to show the current position for user interaction on a computer monitor or other display device that will respond to input from a text input or pointing device.
Answer: Use the jQuery event. pageX and event. pageY pageX and event. pageY in combination with the jQuery offset() method to get the position of mouse pointer relative to an element.
if the above does not work (it didn't in my case - maybe my configuration is little bit different), here is another solution:
you can use this extension function to get the position:
(function ($, undefined) {
$.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;
}
})(jQuery);
the usage is : var position = $("#selector").getCursorPosition()
to insert text at the position:
var content = $('#selector').val();
var newContent = content.substr(0, position) + "text to insert" + content.substr(position);
$('#selector').val(newContent);
That's all.
You may checkout this answer. The insertAtCaret
jquery plugin seems very nice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With