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
Related
I am working on my jquery code to highlight on the text to replace it with anchor tag.
When I click on the button to replace the highlight text with the anchor tag, I want to put the cursor at the end of that highlighted text, example: when I have the full text "My own selected text sentence" and I highlight on the text called "selected" then replace it with anchor tag then I want to put the cursor at the end of the "selected" text just before the "text".
When I highlight on the text called Selected and click on the modal, the text will show as this:
<span class="highlight">Selected</span>
So when I put the url in the input textbox and when I click on the ok button, it will replace the text with the anchor tag just like this:
Selected
But I am unable to put the cursor just after the Selected before the text. Here is what I have tried:
highlight_text = '<span class="highlight">' + Text + '</span>';
anchor_tag = '' + Text + '';
$('#replyMessage').html($("#replyMessage").html().replace(highlight_text, anchor_tag));
placeAtEndOfText(document.querySelector('#replyMessage')
Here is the full code:
$(document).on('click', '#quick_insert-link', function(e) {
e.preventDefault();
var selected_text = window.getSelection ? '' + window.getSelection() : document.selection.createRange().text;
if (selected_text) {
highlightSelection();
$('#quick_linkdialog-text').val(selected_text);
}
});
$(document).on('click', '#quick_ok', function(e) {
if ($('#quick_linkdialog-web-button').is(':checked')) {
var selected_text = window.getSelection ? '' + window.getSelection() : document.selection.createRange().text;
var linkURL = $('#quick_linkdialog-onweb-tab-input').val();
var Text = $('#quick_linkdialog-text').val();
$('.dialog_background_cover').remove();
$('#quick_linkdialog').hide();
$('#replyMessage').focus();
if ($('#quick_linkdialog-onweb-tab-input').val().indexOf('http://') == -1) {
//$('#replyMessage').focus();
if(selectedNode != null && selectedNode.nodeName === 'A') {
selectedNode.href = "http://"+linkURL;
selectedNode.innerText = Text;
}
else {
highlight_text = '<span class="highlight">' + Text + '</span>';
anchor_tag = '' + Text + '';
$('#replyMessage').html($("#replyMessage").html().replace(highlight_text, anchor_tag));
placeAtEndOfText(document.querySelector('#replyMessage').find(anchor_tag));
//document.execCommand('insertHTML', null, '' + Text + '');
}
}
}
});
function highlightSelection() {
var userSelection = window.getSelection();
for(var i = 0; i < userSelection.rangeCount; i++) {
highlightRange(userSelection.getRangeAt(i));
}
}
function placeAtEndOfText(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != 'undefined') {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != 'undefined') {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
When I tried to use placeAtEndOfText function, it will only put the cursor at the end of the text just after "sentence" for the element #replyMessage. I am unable to put the cursor at the end of the "selected" when I try to use placeAtEndOfText function.
Can you please show me an example how I can put the cursor at the end of the text called selected after when I replaced with the anchor tag?
Thank you.
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
I currently have a content editable div which I use as an editor but I'm looking to strip html (not including <br> tags) on paste.
At the moment I have another div <div class="hiddendiv common editor"></div> this one which collects all text and data added to the contenteditable div in order to determine height of the contenteditable div.
I've become confused and unsure how I will do this.
My Question is: How do I strip html formatting (not including <br> tags) whilst inserting text at the cursor caret on paste with jQuery?
HTML:
<div contenteditable='true' id="textarea" class="editor plain-box large-box textarea text common text-content-input quicksand color-dark-grey" data-text="Start typing..."></div>
<div class="hiddendiv common editor"></div>
jQuery
function pasteHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ((node = el.firstChild)) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
document.selection.createRange().pasteHTML(html);
}
}
$('#textarea').on("paste", function() {
var textarea = $('#textarea').html();
var hidden_div = $('.hiddendiv').html(textarea);
var plain_text = hidden_div.text();
$('#textarea').pasteHtmlAtCaret(plain_text);
});
var txt = $('#textarea'),
hiddenDiv = $(document.createElement('div')),
content = null;
txt.addClass('txtstuff');
hiddenDiv.addClass('hiddendiv common editor');
$('body').append(hiddenDiv);
txt.on('keyup input propertychange', function () {
content = $(this).html();
content = content.replace(/\n/g, '<br>');
hiddenDiv.html(content + '<br>');
$(this).css('height', hiddenDiv.height());
});
This may be what you’re looking for:
<div contenteditable="plaintext-only" id="textarea" data-text="Start typing..."></div>
I have added a button to insert some text from a textarea to an editable DIV using this function found on stakoverflow.
function insertAtCursor(){
document.getElementById('myInstance1').focus() ; // DIV with cursor is 'myInstance1' (Editable DIV)
var sel, range, html;
var text = document.getElementById('AreaInsert').value ; // Textarea containing the text to add to the myInstance1 DIV
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode( document.createTextNode(text) );
}
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().text = text;
}
}
With Internet Explorer using document.selection.createRange().text it works fine for line breaks.
With Firefox and Chrome, line breaks of the textarea are not respected, all the text inserted to the editable div from the textarea is on only one line.
How to modify insertAtCursor() to make it works for line breaks with Firefox and Chrome ?
I suggest splitting the text up into separate text nodes, replacing the line breaks with <br> elements, creating a DocumentFragment containing the text and <br> nodes and calling insertNode() to insert it.
Demo: http://jsfiddle.net/timdown/zfggy/
Code:
function insertAtCursor(){
document.getElementById('myInstance1').focus() ; // DIV with cursor is 'myInstance1' (Editable DIV)
var sel, range;
var text = document.getElementById('AreaInsert').value ; // Textarea containing the text to add to the myInstance1 DIV
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var lines = text.replace("\r\n", "\n").split("\n");
var frag = document.createDocumentFragment();
for (var i = 0, len = lines.length; i < len; ++i) {
if (i > 0) {
frag.appendChild( document.createElement("br") );
}
frag.appendChild( document.createTextNode(lines[i]) );
}
range.insertNode(frag);
}
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().text = text;
}
}
I think I found a more appropriate solution for your problem. For demonstration see this Fiddle. See also the css property word-wrap.
Java Script:
var button = document.getElementById('insertText');
button.onclick = function() {
var text = document.getElementById('textarea').value;
document.getElementById('insertHere').innerText = document.getElementById('insertHere').textContent = text
};
To achieve cross browser compatibility, you could also do this:
var isIE = (window.navigator.userAgent.indexOf("MSIE") > 0);
if (! isIE) {
HTMLElement.prototype.__defineGetter__("innerText",
function () { return(this.textContent); });
HTMLElement.prototype.__defineSetter__("innerText",
function (txt) { this.textContent = txt; });
}
I am about to implement Facebook like in integration in my contenteditable div where if i give '$' and some character like 'a' i need a auto-suggestion which should pop up near my caret position.
I need to know how to find out the last character before caret position either in JavaScript for IE and Other browsers. I have access to the Jquery library.
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
})(jQuery);
eg.
var caretPosition = $("#contenteditablediv").getCursorPosition();
var lastchar = getchar(caretposition -1);???
Here's an example of how to do this. It creates a range that starts at the start of the editable element and ends immediately before the caret, gets the range's text and returns the last character of that range.
Demo: http://jsfiddle.net/MH5xX/
function getCharacterPrecedingCaret(containerEl) {
var precedingChar = "", sel, range, precedingRange;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount > 0) {
range = sel.getRangeAt(0).cloneRange();
range.collapse(true);
range.setStart(containerEl, 0);
precedingChar = range.toString().slice(-1);
}
} else if ( (sel = document.selection) && sel.type != "Control") {
range = sel.createRange();
precedingRange = range.duplicate();
precedingRange.moveToElementText(containerEl);
precedingRange.setEndPoint("EndToStart", range);
precedingChar = precedingRange.text.slice(-1);
}
return precedingChar;
}
var editableEl = document.getElementById("editable");
var precedingCharEl = document.getElementById("precedingChar");
function reportCharacterPrecedingCaret() {
precedingCharEl.innerHTML = "Character preceding caret: " + getCharacterPrecedingCaret(editableEl);
}
editableEl.onmouseup = editableEl.onkeyup = reportCharacterPrecedingCaret;
<div contenteditable="true" id="editable">Here is some text. Please put the caret somewhere in here.</div>
<div id="precedingChar" style="font-weight: bold"></div>