How can I toggle a class on selected text? - javascript

I'm trying to create a fairly simple text editor (bold, italic, indent) and need to be able to toggle the class associated with the button on click. I have this code:
var selected = function ()
{
var text = '';
if (window.getSelection) {
text = window.getSelection();
}
return text;
}
$('textarea').select(function(eventObject)
{
console.log(selected().toString());
var selectedtext = selected().toString();
$('#bold-button').click(function () {
$(selectedtext).addClass('bold-text');
});
});
And I can get the selected text to print, but can't get the class added. I've seen other solutions that add the class on click to the entire textarea, but I dont need that. Any help?

You could use surroundContents() like below. Before demo here http://jsfiddle.net/jwRG8/3/
function surroundSelection() {
var span = document.createElement("span");
span.style.fontWeight = "bold";
span.style.color = "green";
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(span);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
But this is not supported less than IE9. And I worked on text selections before and I found them in consistent. Tim Down is very much experienced on selections and most of the answers in SO related to Selections are given my him. He has written a plugin called rangy. You mat try it at https://code.google.com/p/rangy/

Because you are selecting text directly, there is no element to add the class on. textNodes cannot have classes. Instead, try wrapping the text in an element:
$('textarea').select(function(eventObject) {
console.log(selected().toString());
var selectedtext = selected().toString();
$(selectedtext).wrap('<span />').parent().addClass('bold-text');
})
Or you could just wrap it in a b tag, without the class:
$(selectedtext).wrap('<b/>');

Related

How to undo the formatting of a selected text? [duplicate]

I'm trying to make a simple text editor so users can be able to bold/unbold selected text. I want to use Window.getSelection() not Document.execCommand(). It does exactly what I want but when you bold any text, you can't unbold it. I want it in a way that I can bold and unbold any selected text. I tried several things but no success.
function addBold(){
const selection = window.getSelection().getRangeAt(0);
const selectedText = selection.extractContents();
const span = document.createElement("span");
span.classList.toggle("bold-span");
span.appendChild(selectedText);
selection.insertNode(span);
};
.bold-span {font-weight: bold;}
<p contentEditable>Bold anything here and unbold it</p>
<button onclick="addBold()">Bold</button>
This is close to what you want but groups words together so an unselect will remove from whole word. I have not been able to complete this as I have to go, but should be a good starting point.
function addBold(){
const selection = window.getSelection().getRangeAt(0);
let selectedParent = selection.commonAncestorContainer.parentElement;
//console.log(parent.classList.contains("bold-span"))
//console.log(parent)
let mainParent = selectedParent;
if(selectedParent.classList.contains("bold-span"))
{
var text = document.createTextNode(selectedParent.textContent);
mainParent = selectedParent.parentElement;
mainParent.insertBefore(text, selectedParent);
mainParent.removeChild(selectedParent);
mainParent.normalize();
}
else
{
const span = document.createElement("span");
span.classList.toggle("bold-span");
span.appendChild(selection.extractContents());
//selection.surroundContents(span);
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();
}
};
.bold-span {font-weight: bold;}
<p contentEditable>Bold anything here and unbold it</p>
<button onclick="addBold()">Bold</button>
var span = '';
jQuery(function($) {
$('.embolden').click(function(){
var highlight = window.getSelection();
if(highlight != ""){
span = '<span class="bold">' + highlight + '</span>';
}else{
highlight = span;
span = $('span.bold').html();
}
var text = $('.textEditor').html();
$('.textEditor').html(text.replace(highlight, span));
});
});
You could define a function like this where the name of your class is "embolden"

Highlight text in javascript like Evernote Web Clipper

My current solution is:
Get selected html (include text and html tag), namely: selText
highlightText = <span>selText</span>
Find selText in innerHTML of the body or document (or the element which the mouse dragged in)
Replace with highlightText
But if the document is: a a a a a a and user selects the last a. My function will highlight the first or all a.
Any suggestion?
Thank you.
i think your question is duplicated, anyway i just searched the internet and found this article.
Below the final code to achieve what you ask
function highlightSelection() {
var selection;
//Get the selected stuff
if(window.getSelection)
selection = window.getSelection();
else if(typeof document.selection!="undefined")
selection = document.selection;
//Get a the selected content, in a range object
var range = selection.getRangeAt(0);
//If the range spans some text, and inside a tag, set its css class.
if(range && !selection.isCollapsed)
{
if(selection.anchorNode.parentNode == selection.focusNode.parentNode)
{
var span = document.createElement('span');
span.className = 'highlight-green';
range.surroundContents(span);
}
}
}
I also found this library rangy that is an helper you can use to select text but only works with jquery so i prefer the first vanilla-js solution.
var el = $("<span></span>");
el.text(rangy.getSelection().getRangeAt(0).toString());
rangy.getSelection().getRangeAt(0).deleteContents();
rangy.getSelection().getRangeAt(0).insertNode(el.get(0));
rangy.getSelection().getRangeAt(0).getSelection().setSingleRange(range);
On Range and User Selection
You have to select range using Document.createRange that return a Range object before you can use Range.surroundContents(), you could create a range this way.
var range = document.createRange();
range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
In practice you follow this guide to understand range and selection tecniques.
The most important point is contained in this code
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
}
else if (document.selection) { // should come last; Opera!
userSelection = document.selection.createRange();
}
After this you can use
userSelection.surroundContents()

Using JavaScript / jQuery, how do I remove the HTML tags of selected text?

In my application (a basic WYSIWYG text editor) I have a bold button which works, but I need to be able to de-bold text also.
Does anyone have an idea on how to do this?
My code
function bolden ()
{
var range = window.getSelection().getRangeAt(0);
var newNode = document.createElement("b");
range.surroundContents(newNode);
}
function unbolden ()
{
var range = window.getSelection().getRangeAt(0);
$(range).contents().unwrap()
}
Try
function unbolden() {
var range = window.getSelection().getRangeAt(0);
var node = $(range.commonAncestorContainer)
if (node.parent().is('b')) {
node.unwrap();
}
}
Note: If the selected range is under a b element then then entire contents of the element will be unwrapped not just the selected text

How to get the marked text with JS

I want to implement the make bold and put underline functions on my own. For this, I need to get the text which is marked like this:
How can I do this with JavaScript?
var start = element.selectionStart;
var end = element.selectionEnd;
var sel = element.value.substring(start, end);
Based on this and this questions, this fiddle demo shows how you can implement make bold and toggle bold functionality on selected text.
The js function to make selected text bold is:
function makeBold() {
var selection = window.getSelection();
if (selection.rangeCount) {
var range = selection.getRangeAt(0).cloneRange();
var newNode = document.createElement("b");
range.surroundContents(newNode);
selection.removeAllRanges();
selection.addRange(range);
}
}

How can I highlight the text of the DOM Range object?

I select some text on the html page(opened in firefox) using mouse,and using javascript functions, i create/get the rangeobject corresponding to the selected text.
userSelection =window.getSelection();
var rangeObject = getRangeObject(userSelection);
Now i want to highlight all the text which comes under the rangeobject.I am doing it like this,
var span = document.createElement("span");
rangeObject.surroundContents(span);
span.style.backgroundColor = "yellow";
Well,this works fine, only when the rangeobject(startpoint and endpoint) lies in the same textnode,then it highlights the corresponding text.Ex
<p>In this case,the text selected will be highlighted properly,
because the selected text lies under a single textnode</p>
But if the rangeobject covers more than one textnode, then it is not working properlay, It highlights only the texts which lie in the first textnode,Ex
<p><h3>In this case</h3>, only the text inside the header(h3)
will be highlighted, not any text outside the header</p>
Any idea how can i make, all the texts which comes under rangeobject,highlighted,independent of whether range lies in a single node or multiple node?
Thanks....
I would suggest using document's or the TextRange's execCommand method, which is built for just such a purpose, but is usually used in editable documents. Here's the answer I gave to a similar question:
The following should do what you want. In non-IE browsers it turns on designMode, applies a background colour and then switches designMode off again.
UPDATE
Fixed to work in IE 9.
UPDATE 12 September 2013
Here's a link detailing a method for removing highlights created by this method:
https://stackoverflow.com/a/8106283/96100
function makeEditableAndHighlight(colour) {
var range, sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Use HiliteColor since some browsers apply BackColor to the whole block
if (!document.execCommand("HiliteColor", false, colour)) {
document.execCommand("BackColor", false, colour);
}
document.designMode = "off";
}
function highlight(colour) {
var range;
if (window.getSelection) {
// IE9 and non-IE
try {
if (!document.execCommand("BackColor", false, colour)) {
makeEditableAndHighlight(colour);
}
} catch (ex) {
makeEditableAndHighlight(colour)
}
} else if (document.selection && document.selection.createRange) {
// IE <= 8 case
range = document.selection.createRange();
range.execCommand("BackColor", false, colour);
}
}
Rangy is a cross-browser range and selection library that solves this problem perfectly with its CSS Class Applier module. I'm using it to implement highlighting across a range of desktop browsers and on iPad and it works perfectly.
Tim Down's answer is great but Rangy spares you from having to write and maintain all that feature detection code yourself.
var userSelection = document.getSelection();
var range = userSelection.getRangeAt(0);
Instead of surroundContent method you can use the appendChild and extractContents methods this way:
let newNode = document.createElement('mark');
newNode.appendChild(range.extractContents());
range.insertNode(newNode);
function markNode() {
if(document.getSelection() && document.getSelection().toString().length){
let range = document.getSelection().getRangeAt(0);
let newNode = document.createElement('mark');
newNode.appendChild(range.extractContents());
range.insertNode(newNode);
}
else{
alert('please make selection of text to mark');
}
}
function resetContent() {
testMe.innerHTML = `Remember: Read and <strong>stay strong</strong>`;
}
<p id="testMe">Remember: Read and <strong>stay strong</strong></p>
<div><button onclick="markNode()">markNode</button></div>
<div><button onclick="resetContent()">resetContent</button></div>
Could you please elaborate the need of this functionality. If you only want to change the highlight style of the selected text you can use CSS: '::selection'
More Info:
http://www.quirksmode.org/css/selection.html
https://developer.mozilla.org/en/CSS/::selection
Can you try adding a class for the surrounding span and apply hierarchical CSS?
var span = document.createElement("span");
span.className="selection";
rangeObject.surroundContents(span);
In CSS definition,
span.selection, span.selection * {
background-color : yellow;
}
I did not try it. But just guessing that it would work.

Categories

Resources