how to find selected text in html - javascript

how i can to find selected text in a div , in html
for example we have selected from 5 to 11 in this text :
<div id="txt" >This is some <i> text </i> </div>
selected : is some ,
but in html is : id="txt
how to find this and replace between <p> or <span> that other tags to avoid loss of ?
excuse me for my bad english :)

Demo: http://jsfiddle.net/dKaJ3/2/
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
alert(html);
}
Taken from: How to replace selected text with html in a contenteditable element?
Try to find things before you ask ;]

Related

Jquery Set cursor at the end of the highlight text

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.

Replace selected HTML only in a specific div

I want to select the HTML of whatever the user selects in a contenteditable div. I found some code to retrieve the HTML of the selection, but it's not limited to just the div.
What I want to do is copy the selected HTML, wrap tags around it, and then replace the selection with it. So, 'test' would become 'test' for instance.
<div contenteditable="true" class="body" id="bodydiv"></div>
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
}
HI for getting content(text) inside a selected div I have create a little code you can check it out if it works for you :
$(document).ready(function(){
$(document).bind('mouseup', function(){
var content = getSelected();
content = "<b>"+content+"</b>";
$('#selected').html(content);
});
});
function getSelected(){
var t;
if(window.getSelection){
t = window.getSelection();
var start = t.focusOffset;
var end = t.baseOffset;
t = t.anchorNode.data;
t = t.slice(start, end);
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}
And
<div id="selected"></div>
Hope this helps.

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

Editable DIV Add some text at cursor

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; });
}

getSelection without alt attribute and scripts in it?

I'm using window.getSelection () to get the selected text.
But, if i select an image too, it returns also altof an image.
EXAMPLE:
<img src="someSrc.jpg" alt="image_alt" /> My text here ...
if i select an image too, it returns
image_alt My text here ...
But i need only
My text here ...
Is there any way to get only text, without alt?
Thanks much
Try this:
window.getTextSelection = function() {
//First get HTML Fragment of selection
var html = window.getSelection().getRangeAt(0).cloneContents();
//Return only the text
return html.textContent||html.innerText;
}
In some cases you can simply disable the user selection via CSS:
May you also can achieve this by disabling user-select for images:
img {
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
}
The easiest way would be to use the toString() method of selection's Range(s), which is what window.getSelection().toString() is specified to do in the current version of WHATWG's new Range spec (although this is contrary to what some browsers do and may or may not change). The following will work with multiple selected ranges (which Mozilla supports) and also in IE < 9.
jsFiddle: http://jsfiddle.net/timdown/HkP2S/
Code:
function getSelectionRangeText() {
var selText = "";
if (window.getSelection) {
var sel = window.getSelection(), rangeCount = sel.rangeCount;
if (rangeCount) {
for (var i = 0, rangeTexts = []; i < rangeCount; ++i) {
rangeTexts.push("" + sel.getRangeAt(i));
}
selText = rangeTexts.join("");
}
} else if (document.selection && document.selection.type == "Text") {
selText = document.selection.createRange().text;
}
return selText;
}
UPDATE
This solution includes text inside <script> and <style> elements. To remove this, you could use cloneContents() on the selection ranges and traverse the DOM of the resulting document fragments, collecting text only from text nodes not contained within <script> and <style> elements. You could also expand on this to remove text that is inside elements with CSS display: none.
jsFiddle: http://jsfiddle.net/timdown/HkP2S/2/
Code:
function getSelectionRangeText() {
var selText = "", selTextParts = [];
function getNodeText(node) {
if (node.nodeType == 3) {
selTextParts.push(node.data);
} else if (node.hasChildNodes()
&& !(node.nodeType == 1 && /^(script|style)$/i.test(node.tagName))) {
for (var child = node.firstChild; !!child; child = child.nextSibling) {
getNodeText(child);
}
}
}
if (window.getSelection) {
var sel = window.getSelection(), rangeCount = sel.rangeCount;
if (rangeCount) {
for (var i = 0; i < rangeCount; ++i) {
getNodeText(sel.getRangeAt(i).cloneContents());
}
selText = selTextParts.join("");
}
} else if (document.selection && document.selection.type == "Text") {
selText = document.selection.createRange().text;
}
return selText;
}

Categories

Resources