Setting a Range for a Textarea based on User Input - javascript

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/

Related

Get the cursor position in a text that has emojis and insert tags

What's up guys, how's it going? I'm having trouble saving the cursor position and inserting dynamic tags.I'm using the Emojiarea plugin to create a div where I can write texts, insert emojis, templates and tags. https://github.com/mervick/emojionearea
I use the following function below to create a div on my textarea:
$("#email_campaign_description").emojioneArea({
search: false,
recentEmojis: false,
pickerPosition: "right",
events: {
blur: function (editor, event) {
$scope.lastPosition = getCaretCharacterOffsetWithin(editor[0])
},
}
});
The next function returns the last position of my cursor when I click
somewhere in the text:
function getCaretCharacterOffsetWithin(element) {
var caretOffset = 0;
var doc = element.ownerDocument;
var win = doc.defaultView;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
} else if ( (sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
debugger
return caretOffset;
}
And the last function adds dynamic tags to the text:
$scope.chooseTag = function (label) {
var domElement = $('#email_campaign_description');
var emojiElement = domElement[0].emojioneArea;
if (document.selection) {
domElement.focus();
var sel = document.selection.createRange();
sel.text = $scope.tags.model;
domElement.focus();
} else if ($scope.lastPosition) {
var startPos = $scope.lastPosition;
var endPos = startPos + $scope.tags.model[0].length;
emojiElement.setText(emojiElement.getText().substring(0, startPos) + ' ' + $scope.tags.model + ' ' + emojiElement.getText().substring(endPos, emojiElement.getText().length));
domElement.focus();
} else {
emojiElement.setText($scope.tags.model);
domElement.focus();
}
if ($scope.tags.model === '[vendor_name]') {
emojiElement.setText(domElement.val().replace('[vendor_name]', $scope.vendor.name));
}
$scope.campaign.description = $('#email_campaign_description').val();
};
The problem happens that the function that stores the click position in the text does not read emojis. So, if I write a text like: "Hello [emoji], welcome!" and at the end of that text I try to add a tag, my function will not read the emoji, and will insert the tag over the last character of my sentence, in this case "!". Likewise if I add two emojis, my function will not read and insert the tag over the last two characters in this case "o!". The correct thing would be my function to read these two emojis, and add my tag exactly in the desired location, that is: "Hello [emoji], welcome! [Tag]"
What can I do for my function getCaretCharacterOffsetWithin(element) to read emojis as a character, or a space occupied?
The problem is that javascript isn't great at handling Unicode strings.
For example:
"hello".length === 5
"👩🏻‍🦰".length === 7
There are several libraries that can help accurately measure the length of unicode strings. Graphemer is one of them (full disclosure: I published this library).
To fix your getCaretCharacterOffsetWithin(element) function do the following:
Import and instantiate the Graphemer library.
import Graphemer from 'graphemer';
const splitter = new Graphemer();
function getCaretCharacterOffsetWithin(element) {...}
Update the first instance where you count the string length.
caretOffset = preCaretRange.toString().length; // original
caretOffset = splitter.countGraphemes(preCaretRange.toString()); // updated
Update the second instance where you count the string length.
caretOffset = preCaretTextRange.text.length; // original
caretOffset = splitter.countGraphemes(preCaretTextRange.text); // updated
A library-free (Typescript) solution:
correctUnicodeOffset(offset: number, str: string): number {
if (offset < 1) return offset;
return Array.from(str.substr(0, offset)).length;
}
Use it like this:
myOffset = this.correctUnicodeOffset(myOffset, myStr);

Prevent editable div's behavior when typing certain characters

I have the following code taken from Pranav C Balan's answer to my previous question:
var div = document.getElementById('div');
div.addEventListener('input', function() {
var pos = getCaretCharacterOffsetWithin(this);
// get all red subtring and wrap it with span
this.innerHTML = this.innerText.replace(/red/g, '<span style="color:red">$&</span>')
setCaretPosition(this, pos);
})
// following code is copied from following question
// https://stackoverflow.com/questions/26139475/restore-cursor-position-after-changing-contenteditable
function getCaretCharacterOffsetWithin(element) {
var caretOffset = 0;
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
} else if ((sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}
function setCaretPosition(element, offset) {
var range = document.createRange();
var sel = window.getSelection();
//select appropriate node
var currentNode = null;
var previousNode = null;
for (var i = 0; i < element.childNodes.length; i++) {
//save previous node
previousNode = currentNode;
//get current node
currentNode = element.childNodes[i];
//if we get span or something else then we should get child node
while (currentNode.childNodes.length > 0) {
currentNode = currentNode.childNodes[0];
}
//calc offset in current node
if (previousNode != null) {
offset -= previousNode.length;
}
//check whether current node has enough length
if (offset <= currentNode.length) {
break;
}
}
//move caret to specified offset
if (currentNode != null) {
range.setStart(currentNode, offset);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
<span contenteditable="true" id="div" style="width:100%;display:block">sss</span>
It has a editable <div> where the user can input and it automatically colors the word red as red just like some code editors color key words like HTML tags, strings, functions, etc.Type "red" and you will understand what I mean.
The issue I'm having is, when I type "<", it deletes all the characters in front of it unless it finds a ">" where it will stop. Another error happens if you type "&#1" (or any other number instead of 1 really).
Any ideia on how to prevent this behavior?
You're running into this problem because you're expecting the user to be able to input HTML-like entities such as <xyz... or { but don't want to parse that input as HTML, but at the same time, you're yourself putting html elements in the same div and you want that to be parsed as HTML. So there are two ways you can go about this:
Keep the input and presentation separate. So user can input anything, which you'll sanitize and display in an output box.
Or... change the addEventListener function:
div.addEventListener('input', function() {
var pos = getCaretCharacterOffsetWithin(this);
var userString = sanitizeHTML(this.innerText);
// get all red subtring and wrap it with span
this.innerHTML = userString.replace(/red/g, '<span style="color:red">$&</span>')
setCaretPosition(this, pos);
})
This would work in most scenarios, but it'd break (badly) if you're expecting user to input HTML too, for example <span class="red" style="color: red">red</span> would become horribly mutilated. Other than that, you're good to go. Get sanitizeHTML from here: https://github.com/punkave/sanitize-html

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.

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