How to get the marked text with JS - javascript

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

Related

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 can I toggle a class on selected text?

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/>');

Getting already selected text

By using following code I am getting the selected text's startindex and the selected text itself. I am storing them in a local database. I am changing the selected text background color to yellow.
var mainDiv = document.getElementsByTagName("body")[0];
var sel = getSelectionCharOffsetsWithin(mainDiv);
var selectedText = window.getSelection();
location.href = selectedText + '*' + sel.start; // this is to call iOS function.
var range = window.getSelection().getRangeAt(0);
var span = document.createElement("span");
span.style.backgroundColor = "yellow";
span.setAttribute("id", sel.start);
range.surroundContents(span);
Now, I am doing something else, and again I come back to same page. Here now I want to show previously selected text as highlighted.
Use Rangy , nothing beats it , does exactly what your trying
Rangy
Have a look at this demo

Finding indices of highlighted text

I'm trying to save information about text that a user has highlighted in a webpage. Currently I'm using the getSelection method shown below:
var txt = '';
if (window.getSelection){txt = window.getSelection();}
else if (document.getSelection){txt = document.getSelection();}
else if (document.selection){txt = document.selection.createRange().text;}
else return;
to retrieve the highlighted text. Then I'm searching through the entire text body and storing the indices of the highlighted text. The getSelection method only returns what text is highlighted so the problem is that if the highlighted text appears multiple times in the text body, the search could find the wrong repeat of the text and thus save the wrong indices.
Any ideas how to ensure that I'm saving the right indices?
Thanks!
QuirksMode has an article about this.
You'd probably be interested in this code:
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
}
else if (document.selection) { // should come last; Opera!
userSelection = document.selection.createRange();
}
var rangeObject = getRangeObject(userSelection);
function getRangeObject(selectionObject) {
if (selectionObject.getRangeAt)
return selectionObject.getRangeAt(0);
else { // Safari!
var range = document.createRange();
range.setStart(selectionObject.anchorNode,selectionObject.anchorOffset);
range.setEnd(selectionObject.focusNode,selectionObject.focusOffset);
return range;
}
}

Categories

Resources