Reputation: 7122
I'm trying to use javascript & css to create a little tool that will allow the user to select an area of text(whole word, part of a word, single character) with the mouse and then click a button that will then bold that selection.
I have 2 pieces working: I can bold the whole area, and I can write the mouse selection to the console.
But I can't figure out how to only bold the portion of text that was selected with the mouse.
I have a jsfiddle here: http://jsfiddle.net/75EwZ/4/
Here's the code:
$(".boldtrigger").click(function() {
var selection = getSelText();
console.log('selected value', selection);
//only bold text that is selected
//get contents of .text
//replace selected section with <span class="selectedText"></span>
//ex: user selects the word "the" with the mouse:
//<div class="text">Testing the waters</div> becomes:
//<div class="text">Testing <span class="selectedText">the</span> waters</div>
//then bold contents of .selectedText
$(".text").toggleClass("bold");
});
function getSelText()
{
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;
return txt;
}
thanks!
Upvotes: 3
Views: 1192
Reputation: 1
Go through this tutorial Get Selected text through jquery. use the same code to get the selected section then on button click replace the same with <b>"selected text"</b>
.
Upvotes: -1
Reputation: 14796
You need to use the method surroundContents on the Range of the selection. Unfortunately that function is not supported in every browser, so you will need to take care of that.
var range = selection.getRangeAt(0);
if(selection.toString().length > 2){
var newNode = document.createElement("span");
newNode.setAttribute("class", "selectedText");
range.surroundContents(newNode);
}
Working demo here.
See the documentation here.
Upvotes: 5
Reputation: 31
You should see the document.execCommand method : https://developer.mozilla.org/fr/docs/Rich-Text_Editing_in_Mozilla
Upvotes: 1