Insert span-node and continue writing - javascript

I have a problem adding nodes to a editable div.
I want to add highlighted text in a span and after that the cursor should be outside the added span.
Right now the cursor is inside the added span.
I have created a Fiddle to demonstrate it:
http://jsfiddle.net/4N4ZD/633/
Here is some code:
function insertNodeAtCaret() {
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0);
range.collapse(false);
var span = document.createElement('span');
span.innerHTML = 'TEXT';
span.style.background = 'yellow';
range.insertNode(span);
range = range.cloneRange();
range.selectNodeContents(span);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
}
}
}

Found a solution. Here is a fiddle: http://jsfiddle.net/4N4ZD/638/
The trick is to add a new text-span and use the methode 'setStartAfter' like so:
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var span = document.createElement('span');
span.innerHTML = 'TEXT';
span.style.background = 'yellow';
range.insertNode(span);
var textNode = document.createTextNode('\u00A0');
range.setStartAfter(span);
range.insertNode(textNode);
range.setStartAfter(textNode);
range.collapse(true);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}

Related

Autocomplete Suggestion on <p> Tag Without Dropdown

I'm trying to make autocomplete (without dropdown) to a contenteditable paragraph tag. How to select remaining suggested letters in contenteditable p tag with javascript/jQuery while user typing?
// On typing
$(document).on('input', '.cell-input', function(e) {
var userInput = e.target.innerText;
// Suggested 'Bond' to user, because user typed (assumption) 'B'
e.target.innerText = 'Bond';
// Select
$(e.target).selectText(1, 3);
});
// To select
jQuery.fn.selectText = function(startPos, endPos){
var doc = document;
var element = this[0];
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
}
else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
Select all is working fine. Then I tried adding:
selection.moveEnd("character", endPos);
selection.moveStart("character", startPos);
or
range.moveEnd("character", endPos);
range.moveStart("character", startPos);
.. but no luck. Am I in the right direction? Please advice.
Using setStart() and setEnd()
$(document).on('input', '.cell-input', function(e) {
var userInput = e.target.innerText;
// Suggested 'Bond' to user, because user typed (assumption) 'B'
e.target.innerText = 'Bond';
// Select
$(e.target).selectText(1, 4);
});
// To select
jQuery.fn.selectText = function(startPos, endPos) {
var doc = document;
var element = this[0];
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.setStart(element.firstChild, startPos);
range.setEnd(element.firstChild, endPos);
selection.removeAllRanges();
selection.addRange(range);
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="cell-input" contenteditable="true">B</p>
Note: Using element.firstChild may not work with HTML child nodes

How to get the row and column of the selected word in a text area?

I have a text area that users can enter text in. When they select text I'd like to get the row and column of the selected text (or cursor) if they do not select any text.
The example below is using the on focus event. It should use a cursor change or selection change event.
document.getElementById('textarea').onselectionchange = onFocusHandler;
document.getElementById('textarea').onselect = onFocusHandler;
document.getElementById('textarea').onfocus = onFocusHandler;
document.getElementById('textarea').onmouseup = onFocusHandler;
document.getElementById('textarea').onselectionstart = onFocusHandler;
function onFocusHandler(event){
var textarea = document.getElementById('textarea');
var value = textarea.value;
var anchorPosition = 0;
var activePosition = 0;
var userSelection;
var range;
console.log(event.type);
if (window.getSelection) {
//console.log("1");
userSelection = window.getSelection();
//console.log(userSelection);
//range = userSelection.getRangeAt(0);
//console.log(range);
}
else if (document.selection) {
userSelection = document.selection.createRange();
}
console.log("Cursor:" + userSelection.anchorOffset);
return;
if (userSelection.getRangeAt) {
//range = userSelection.getRangeAt(0);
}
else {
range = document.createRange();
range.setStart(userSelection.anchorNode, userSelection.anchorOffset);
range.setEnd(userSelection.focusNode, userSelection.focusOffset);
}
//console.log(range);
textarea.focus();
if (textarea.setSelectionRange) {
textarea.setSelectionRange(anchorPosition, activePosition);
}
else {
var range = textarea.createTextRange();
range.collapse(true);
range.moveEnd('character', activePosition);
range.moveStart('character', anchorPosition);
range.select();
}
};
<textarea id="textarea" style="width:100%;height:100px">Hello world.
It's a nice day.
Go outside and get some sun.
</textarea>
<span id="row">Row</span>

JQuery selector for highlighted text

I want to know how to select Highlighted text using JQuery selector.
For example, to select elements with a class, you use .class, for IDs, you use #id.
What do I use for highlighted text so that I can (for example) hide them:
$("Highlighted text").hide();
What is the highlighted text selector, and how to hide highlighted text?
This is one your are looking for i believe:
text = window.getSelection().toString();
DEMO
Hide selected/highlighted text javascript
You have to get parent of Element from DOM:
function getSelectionParentElement() {
var parentEl = null, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
parentEl = sel.getRangeAt(0).commonAncestorContainer;
if (parentEl.nodeType != 1) {
parentEl = parentEl.parentNode;
}
}
} else if ( (sel = document.selection) && sel.type != "Control") {
parentEl = sel.createRange().parentElement();
}
return parentEl;
}
NEW DEMO
Update
Fixed demo to hide text we have to find startOffset
function getStartOffset() {
var sel = document.selection, range, rect;
var x = 0, y = 0;
if (sel) {
if (sel.type != "Control") {
range = sel.createRange();
range.collapse(true);
}
} else if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0).cloneRange();
if (range.getClientRects) {
range.collapse(true);
}
}
}
return range.startOffset;
}
Updated DEMO
if($("idDiv").html().contains('Highlighted text')==true)
{
var a=$("#idDiv").html();
a=a.replace("Highlighted text","<p id='highlightedtext'>Highlighted text</p>");
$("#idDiv").html(a);
$("#highlightedtext").hide();
}
The above code check the highlighted text from the div and if it found it set that text in p tag with id and using that id you can hide it

Edit and Select Text using jQuery

I have a text field which can be edited using click and i am doing it in jQuery.
Now i was wondering how can i select all the text in box when i click EDIT button
Fiddle Link
Code for edit
$('.edit').click(function () {
$(this).siblings('.edit-section').attr('contenteditable', 'true');
$(this).siblings('.edit-section').attr('style', 'border:2px solid;');
$(this).attr('style', 'display:none;');
$(this).siblings('.done').attr('style', 'display:li;');
});
I cannot add separate click function for .edit-section
Try,
$('.edit,.done').click(function () {
var section = $(this).siblings('.edit-section');
var isEdit = $(this).is('.edit');
section.prop('contenteditable',isEdit).css('border',isEdit?"2px solid":"none");
$('.edit').toggle(!isEdit);
$('.done').toggle(isEdit);
if(isEdit){section.focus(); document.execCommand('selectAll',false,null); }
});
DEMO
Source
Demo
jQuery.fn.selectText = function () {
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
$(".edit").click(function () {
$(".edit-section").selectText();
});
from : Selecting text in an element (akin to highlighting with your mouse)
Possible duplicate - Programmatically select text in a contenteditable HTML element?
Copied following function from the answer.
function selectElementContents(el) {
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
var el = document.getElementById("foo");
selectElementContents(el);
Updated JS-Fiddle - http://jsfiddle.net/vishwanatharondekar/zSwBL/5/
Try
jQuery.fn.selectText = function(){
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
$("button").click(function() {
$("#editable").selectText();
});
JSFiddle
Refence: How to select all text in contenteditable div?

set cursor between 2 letters in contenteditable

How do I set the cursor between the a and the b below?
<div contenteditable = true id = "test">
abcdefg
</div>
I have tried to play with ranges, but nothing is working for me. The below code selects the entire text, and there is no cursor. (This code is for Chrome)
sel = window.getSelection();
range = document.createRange();
node = document.getElementById("test");
range.setStart(node, 0);
range.setEnd(node, 1);
sel.addRange(range);
This should work:
function setSelectionRange(aNode, aOffset) {
aNode.focus();
var sel = window.getSelection(),
range = sel.getRangeAt(0);
range.collapse(true);
range.setStart(aNode.childNodes[0], aOffset),
sel.removeAllRanges();
sel.addRange(range);
}
setSelectionRange(document.getElementById("test"), 1);
http://jsfiddle.net/5a9uD/1/
If you look to MDN documentation https://developer.mozilla.org/en-US/docs/Web/API/range.setStart you will see that this interface use a node not an element.

Categories

Resources