suppose to be we have a paragraph with this content " Hi , It's a new question in stackoverflow!"
and when we are selecting something in this paragraph , it's turn to be Red .for example we selected stackoverflow & then it turn to <span class="red">stackoverflow</span>.how can we do this with Javascript?
here is my codes :
var x = {};
x.getSelected = function() {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}
$(document).ready(function() {
var selectedText;
$(document).bind("mouseup", function() {
selectedText = x.getSelected()
if (selectedText !=''){
alert(selectedText);
//Now I wanna set new content for selected item but not working
a=selectedText;
selectedText.html("<span class='red'>"+a+"</span>");
}
});
});
.red {
color : red;
}
<p>suppose to be we have a paragraph with this content " Hi , It's a new question in stackoverflow!" and when we are selecting something in this paragraph , it's turn to be Red .for example we selected stackoverflow & then it turn to .how can we do this with Javascript? </p>
...when we are selecting something in this paragraph , it's turn to be
Red...
You could have a stab at the styleWithCSS command of the editing API, execCommand that is.
However, before proceeding please note that:
This spec is incomplete and it is not expected that it will advance
beyond draft status. Authors should not use most of these features
directly, but instead use JavaScript editing libraries. The features
described in this document are not implemented consistently or fully
by user agents, and it is not expected that this will change in the
foreseeable future.... This spec is to meant to help implementations
in standardizing these existing features. It is predicted that in the
future both specs will be replaced by Content Editable Events and
Input Events....
Having clarified that, the following will work in most modern browsers viz. Edge, FireFox and Chrome that I could test in.
By default the foreColor command of execCommand wraps the selected text with a font tag, which is deprecated. So, you need to use the styleWithCSS command. Now this works with the editing API, which means that the element you are trying to work with, should have its contentEditable attribute set.
To work around this, you can temporarily set this attribute just before changing the color in the selected text fragment and then resetting the attribute once done.
Given your paragraph like this:
<p id="p">
Hi , It's a new question in StackOverflow!
</p>
When you select the word StackOverflow, the following code will result in this...
<p id="p">
Hi , It's a new question in <span style="color: rgb(255, 0, 0);">StackOverflow</span>!
</p>
... wrapping your selected text in a span with the style applied.
Fiddle: http://jsfiddle.net/abhitalks/j9w6dj7m/
Snippet:
p = document.getElementById('p');
p.addEventListener('mouseup', setColor);
function setColor() {
p.setAttribute('contentEditable', true);
document.execCommand('styleWithCSS', false, true);
document.execCommand('foreColor', false, "#f00");
p.setAttribute('contentEditable', false);
}
<p id="p" contentEditable="false">
Hi , It's a new question in stackoverflow!
</p>
Edit:
Now that you have added code (and what you have already tried) in your question, you could use the range selection to do what you are after.
Specifically, you will need to learn:
selection: https://developer.mozilla.org/en-US/docs/Web/API/Selection, this you have already done. Cheers!
range: https://developer.mozilla.org/en-US/docs/Web/API/Range/Range, because you will be dealing with ranges here
selection.getRangeAt(): https://developer.mozilla.org/en-US/docs/Web/API/Selection/getRangeAt, because you will need to extract the selected text as a range object
range.surroundContents(): https://developer.mozilla.org/en-US/docs/Web/API/range/surroundContents, because you will need to surround the selected text range with a span.
Putting it all together all you have to do is (explanation in code comments):
function setClass() {
var selection = x.getSelected(), range, // you have already done this
span = document.createElement("span"); // create a span element
span.classList.add('red'); // add the class to the span
if (selection != '') {
range = selection.getRangeAt(0); // get the range from selected text
range.surroundContents(span); // surround the range with span
}
}
Fiddle 2: http://jsfiddle.net/abhitalks/kn0u5frj/
Snippet 2:
var x = {},
p = document.getElementById('p');
p.addEventListener('mouseup', setClass);
function setClass() {
var selection = x.getSelected(), range,
span = document.createElement("span");
span.classList.add('red');
if (selection != '') {
range = selection.getRangeAt(0);
range.surroundContents(span);
}
}
x.getSelected = function() {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}
.red { color: #f00; }
<p id="p">
Hi , It's a new question in stackoverflow!
</p>
You can use the getSelection() method
Below is the example:
Repeated Question:
How to get selected text in textarea?
You can use CSS with :: selection http://caniuse.com/#search=%3A%3Aselection
::selection {
background: #ffb7b7; /* WebKit/Blink Browsers */
}
::-moz-selection {
background: #ffb7b7; /* Gecko Browsers */
}
Or javascript with range
Related
I have code to bold/unbold scripts via Window.getSelection()
I got it from this answer: Bold/unbold selected text using Window.getSelection()
It really works without problems .
But when I looked for another code to make the selection inside a div specified with id
I found this answer :
How to getSelection() within a specific div?
When I try to combine the first answer with the second answer
I found it doing bold and not unbold
My Code :
function addBold(){
/*
answer 1
https://stackoverflow.com/questions/63364212/bold-unbold-selected-text-using-window-getselection
answer 2
https://stackoverflow.com/questions/38758713/how-to-getselection-within-a-specific-div
*/
// answer 2
if(window.getSelection().baseNode.parentNode.id != "editor") return;
// end answer 2
// answer 1
const selection = window.getSelection().getRangeAt(0);
let selectedParent = selection.commonAncestorContainer.parentElement;
let mainParent = selectedParent;
if(selectedParent.closest("b"))
{
//Unbold
var text = document.createTextNode(selectedParent.textContent);
mainParent = selectedParent.parentElement;
mainParent.insertBefore(text, selectedParent);
mainParent.removeChild(selectedParent);
mainParent.normalize();
}
else
{
const span = document.createElement("b");
span.appendChild(selection.extractContents());
selection.insertNode(span);
mainParent.normalize();
}
//selection is set to body after clicking button for some reason
//https://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
// end answer 1
};
<div id="editor" contenteditable="true">
You are the programmers of the future
</div>
<button onclick="addBold()">Bold</button>
Like I said when you combined the two an
swers
Makes bold and ignores unbold
If you delete the first line of the validation condition,
if(window.getSelection().baseNode.parentNode.id
It will work successfully Bold/Unbold
that window.getSelection().baseNode.parentNode.id
When creating bold
The parent element of the text is obtained
and find it
Text
Therefore, he did not reach the main father element who kissed him
So replace the first line with this line and it works successfully
Replace
window.getSelection().baseNode.parentNode.id != "editor"
To
window.getSelection().focusNode.parentElement.closest("#editor").id != "editor"
I'm building a chrome extension where selected text can have different highlighting styles applied to it. I used ranges to get this all to work, and I clone the range, put a span around it, and then delete the range and replace it with the cloned one. Everything seems fine except I've somehow managed to disable right clicking by triggering this behavior through the extension. I've narrowed it down the single line of range.surroundContents(span), but here's the full code section:
// Determines the selected text
document.onmouseup = function() {
var selection = document.getSelection();
selection = getSelectedText(color);
};
// Finds the text selected in the page, spans it, and gives it a class
function getSelectedText(inputColor) {
var span = document.createElement('span');
span.setAttribute('class', inputColor);
if(document.getSelection) {
var selection = document.getSelection();
if(selection.rangeCount == true) {
var range = selection.getRangeAt(0).cloneRange();
range.surroundContents(span);
selection.removeAllRanges();
selection.addRange(range);
}
}
}
Is there a way I can counter this? I've already tried using document.oncontextmenu = false directly following the problem line, but that's not bringing back right click. I also tried replacing it with newNode.appendChild(range.extractContents()); range.insertNode(newNode) as recommended by https://developer.mozilla.org/en-US/docs/Web/API/Range/surroundContents but then instead of highlighting text, it seems to just be removing it from the page.
#wOxxOm answered my question in a comment, but a setTimeout() is what worked. So for anyone else who might have a similar issue in the future:
// Finds the text selected in the page, spans it, and gives it a class
function getSelectedText(inputColor) {
var span = document.createElement('span');
span.setAttribute('class', inputColor);
if(document.getSelection) {
var selection = document.getSelection();
if(selection.rangeCount == true) {
var range = selection.getRangeAt(0).cloneRange();
setTimeout(function(){
range.surroundContents(span);
selection.removeAllRanges();
selection.addRange(range);
}, 100)
}
}
}
I have a contenteditable div (with id 'editor1') that allows users to input text. There is then a function that allows them to color any highlighted text. My js uses window.getSelection().getRangeAt(0), but the issue with this is that they can highlight words outside of the div and their color will change as well. So far; I've tried:
function red(){
{
var getText = document.getElementById("editor1").innerHTML;
var selection = getText.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement("span");
span.style.color = "red";
span.appendChild(selectedText);
selection.insertNode(span);
}
}
Fiddle: https://jsfiddle.net/xacqzhvq/
As you can see, if I highlight "this will become red as well", I can use the button to make that red too.
How can I only color the highlighted text only within the editor1 div?
You are able to get the node element from the selection using .baseNode. From there you can get the parent node and use that for comparison.
function red(){
// If it's not the element with an id of "foo" stop the function and return
if(window.getSelection().baseNode.parentNode.id != "foo") return;
...
// Highlight if it is our div.
}
In the example below I made the div have an id that you can check to make sure it's that element:
Demo
As #z0mBi3 noted, this will work the first time. But may not work for many highlights (if they happen to get cleared). The <span> elements inside the div create a hierarchy where the div is the parent elements of many span elements. The solution to this would be to take traverse up through the ancestors of the node until you find one with the id of "foo".
Luckily you can use jQuery to do that for you by using their .closest() method:
if($(window.getSelection().baseNode).closest("#foo").attr("id") != "foo") return;
Here is an answer with a native JS implemented method of .closest().
Are you looking for this,
//html
<body>
<p id='editor1'>asdf</p>
<button onclick='red()'>
RED
</button>
</body>
//JavaScript
window.red = function(){
//var getText = document.getElementById("editor1").innerHTML;
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement("span");
span.style.color = "red";
span.appendChild(selectedText);
selection.insertNode(span);
}
Plunker: https://plnkr.co/edit/FSFBADoh83Pp93z1JI3g?p=preview
Try This Code :
function addBold(){
if(window.getSelection().focusNode.parentElement.closest("#editor").id != "editor") return;
const selection = window.getSelection().getRangeAt(0);
let selectedParent = selection.commonAncestorContainer.parentElement;
let mainParent = selectedParent;
if(selectedParent.closest("b"))
{
//Unbold
var text = document.createTextNode(selectedParent.textContent);
mainParent = selectedParent.parentElement;
mainParent.insertBefore(text, selectedParent);
mainParent.removeChild(selectedParent);
mainParent.normalize();
}
else
{
const span = document.createElement("b");
span.appendChild(selection.extractContents());
selection.insertNode(span);
mainParent.normalize();
}
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
};
<div id="editor" contenteditable="true">
You are the programmers of the future
</div>
<button onclick="addBold()">Bold</button>
I got the code and added my edits from those following answers :
Bold/unbold selected text using Window.getSelection()
getSelection().focusNode inside a specific id doesn't work
Is there any way to detect with JavaScript/jQuery if an element is strike-through and underlined.
So let's say we have:
<u><s>text here.</s>other text here.</u>
Is it possible to detect if the text within <s> is also underlined?
*Ideally, it would not be allowed to look if <u> has any <s> children.
I've been toying around with it and it seems peculiar that both styles use the same CSS property, which in turn makes me wonder how it even works in the first place.
To make my problem clearer:
I'm playing around with a self-made wysiwyg editor, for usability reasons I'm trying to implement a listener on the text which alters (lights up) editing buttons. e.g. when a part of text is bold the "B" button changes to an active state. I'm currently handling this by getting the element at the cursor and checking if the element is bold or inherits it.
The problem with underline and striketrough is that they are neither overwriting the text-decoration attribute of each other, and are not visible in css
when I put the cursor on a underlined text-fragment, the text-decoration property only shows as underline, while the text is both underline and line-through. In such situations I cannot know what the exact relation is between the <u> element and the <s> element; the <s> element could be 100 parents back as far as I could know.
A lot of text, but I hope it kinda clears up my situation.
Here is the robust way of doing it. #Cheery answer works well but it fails if italic or underline or any other font-style provided through CSS. Credit is given to Tim Down for his numerous answers for these kind of questions.
function checkState(element, check) {
var doc = document;
var text = doc.getElementById(element);
if (doc.body.createTextRange) { // ms
var range = doc.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) { // moz, opera, webkit
var selection = window.getSelection();
var range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
var range, checked = false;
if (window.getSelection) {
var sel = window.getSelection();
if (sel && sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
document.designMode = "on";
sel.removeAllRanges();
sel.addRange(range);
}
}
if (document.queryCommandState) {
checked = document.queryCommandState(check);
}
if (document.designMode == "on") {
document.designMode = "off";
}
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
return checked;
}
alert(checkState('c', 'underline')); // italic, bold etc..
var str = '<u><s>text here.</s>other text here.</u>';
var el = $('<div>').html(str);
alert($('u s', el).length);
what if the combination is or even something like
so what, check inverse too..
var str = '<s><div><u></u></div><p><u></u></p></s>';
var el = $('<div>').html(str);
alert($('u s', el).length || $('s u', el).length);
if the initial string is not a valid html then you do not know how some browsers will behave at its output.
ps: made some simple example, by click..
$(function(){
$('.wrapper').on('click', '*', function() {
var styles = ['line-through', 'underline'], counter = [0, 0], tags = ['S', 'U'];
$(this).parentsUntil('.wrapper').andSelf().each(function() {
var current = $(this).css('text-decoration'), $tag = $(this)[0];
$.each(styles, function(index, style) {
if (current.indexOf(style) > -1 || $tag.tagName == tags[index]) counter[index] += 1;
});
});
var results = [];
if (counter[0] > 0) results.push('striked');
if (counter[1] > 0) results.push('underlined');
alert(results.join(' and '));
return false;
});
});
.strike {
text-decoration: line-through;
}
.underline {
text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class='wrapper'>
<div class='strike'>
striked <u>underlined</u>
</div>
<div class='underline'>
underlined <s>striked</s>
</div>
</div>
A somewhat horrible approach, but the only way I could see that doesn't involve explicitly checking nesting, or relying on default CSS surviving any theming (<s> won't always, necessarily, have text-decoration: line-through;, similarly <u> won't always, necessarily, have text-decoration: underline;):
// the text-decoration styles you want to find:
var styles = ['line-through', 'underline'];
// finding all elements within the <body>, and
// filtering them:
var underlinedAndLineThrough = $('body *').filter(function() {
// caching because of re-use:
var self = $(this),
decor = self.css('text-decoration');
// if the 'text-decoration' style is found in the array of styles we're
// looking for:
if (styles.indexOf(decor) > -1) {
// we add that style as a class-name to the current element, and all
// descendants:
self.find('*').add(self).addClass(decor);
// we return the current element (to keep it in the collection):
return self;
}
// filtering again:
}).filter(function(){
// we keep the current element of the collection if it has all the css styles
// we're looking for:
return $(this).is('.' + styles.join('.'));
});
console.log(underlinedAndLineThrough);
JS Fiddle demo.
References:
JavaScript:
Array.prototype.indexOf().
Array.prototype.join().
jQuery:
add().
addClass().
filter().
find().
is().
I need to select text from different paragraphs and make a span for showing this text. See this example:
<p> this is a text </p>
<p>hello ever one </p>
Now what I want is that if I select text from the web view in my iPhone app it highlights it in a different color. For this I am making a span and setting its style. It works fine for the same paragraph but not for different paragraphs. See this:
<p> this <span class="blue">is a </span> text </p>
Class blue declares its style and it works fine, but the following does not work:
<span class="blue">
<p> this is a text </p>
<p>hello ever </span> one </p>
For solving this problem I need two spans for both paragraphs. So how can I check where the new paragraph starts? The correct HTML code is:
<span class="blue">
<p> this is a text </p></span>
<p> <span class="blue"> hello ever </span> one </p>
I need to get this HTML string but I get the wrong one. I have written a JavaScript function that gets the selection and makes a span according to selection. But on selecting text from two paragraphs it does not work because it gives the wrong section of HTML code. See my JavaScript code:
function highlightsText()
{
var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var div;
var newDate = new Date;
var randomnumber= newDate.getTime();
var imageTag = document.createElement("img");
imageTag.id=randomnumber;
imageTag.setAttribute("src","notes.png");
var linkTxt = document.createElement("a");
linkTxt.id=randomnumber;
linkTxt.setAttribute("href","highlight:"+randomnumber);
div = document.createElement("span");
div.style.backgroundColor = "yellow";
div.id=randomnumber;
linkTxt.appendChild(imageTag);
div.appendChild(selectionContents);
div.appendChild(linkTxt);
range.insertNode(div);
return document.body.innerHTML+"<noteseparator>"+randomnumber+"<noteseparator>"+range.toString();
}
Please provide a solution that can resolve this problem.
You could do something along the lines of:
Get highlighted section of text.
Insert span tag at the first point.
For every tag that you come accross within the highlighted text:
If it's an opening tag, check if it's corresponding closing tag is in the highlighted text.
If both opening and closing tags are within the text ignore them and move to the next point after the corresponding closing tag.
If only the opening tag or only the closing tag is present, then insert before the tag and after the tag.
Insert span closing tag at the end of the highlighted text.
Possible problem:
span is intented to group inline elements and not block elements so if your highlighted text includes block elements you could have problems. You could use div instead of span to solve this or you could add some checks to distinguish between inline and block tags.
To look at tag matching:
http://haacked.com/archive/2004/10/25/usingregularexpressionstomatchhtml.aspx
To find if the matching closing tag of an element is in the higlighted text (not tested):
function checkClosingTag(position)
{
//Find position of next opening or closing tag along the
//string of highlighted text.
//Return 0 if no more tags.
var nextTag = findNextTag(position);
if(nextTag == 0)
{
return 0;
}
if(!isOpeningTag(nextTag))
{
return nextTag;
}
var nextTagClose = checkClosingTag(nextTag);
if(nextTagClose == 0)
{
return 0;
}
return checkClosingTag(nextTagClose);
}
This looks like a fairly involved problem though - I don't have time to write the code for you but you should be able to work out a way of doing it from here.
some change in your code can work
see this line of codes
function highlightsText()
{
var range, sel;
if (window.getSelection)
{
sel = window.getSelection();
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
if ( !document.execCommand("HiliteColor", false, "yellow") ) {
document.execCommand("BackColor", false, "yellow");
}
document.designMode = "off";
}
else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.execCommand("BackColor", false, "yellow");
}
var newDate = new Date;
var randomnumber= newDate.getTime();
var nodeList = document.querySelectorAll(".Apple-style-span");
for (var i = 0, length = nodeList.length; i < length; i++) {
nodeList[i].id = randomnumber;
}
var div = document.getElementById(randomnumber);
var imageTag = document.createElement("img");
imageTag.id=randomnumber;
imageTag.setAttribute("src","notes.png");
var linkTxt = document.createElement("a");
linkTxt.id=randomnumber;
linkTxt.setAttribute("href","highlight:"+randomnumber);
div.appendChild(linkTxt);
range.insertNode(div);
return document.body.innerHTML+"<noteseparator>"+randomnumber+"<noteseparator>"+range.toString();
}
You need make some adjustments in this code.
Since your goal (based on what you stated in your question) is to highlight selected text with a different color, here is a solution to that goal.
The HTML5BoilerPlate project includes styles to control the selection color (line 52 in the style.css file)
Here's the CSS for it:
/* Remove text-shadow in selection highlight: h5bp.com/i
*
* These selection declarations have to be separate
*
* Also: hot pink! (or customize the background color to match your design)
*/
::-moz-selection { background: #fe57a1; color: #fff; text-shadow: none; }
::selection { background: #fe57a1; color: #fff; text-shadow: none; }