1

I want to do something similar to what this website and wordpress does. When a user highlights text on the screen, then clicks a button on the toolbar it will wrap an html tag around the text. In jquery I would probably use the .wrap class but how would I detect if the user highlighted something.

For example, when the user writes Hello World then clicks on the bold button it will say <b>Hello World</b>

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
johnbumble
  • 630
  • 1
  • 10
  • 18
  • This might help: http://stackoverflow.com/questions/5001608/how-to-know-if-the-text-in-a-textbox-is-selected – Nic Aug 03 '16 at 08:05

3 Answers3

0

Get the text of the html element which is wrapping the text, then add as html the text embedded in the <b> tag.

See jQuery DOM Manipulation for tutorials.

cdaiga
  • 4,861
  • 3
  • 22
  • 42
0

This mainly requires (1) accessing the selectionStart and selectionEnd properties of the input/textarea element and (2) replacing the substring of the value property across that range with the same text, but wrapped in the desired start and end tags. Also, I think it makes sense to reselect the replaced text, which requires a couple of calls to select() and setSelectionRange(). Also, if there's no selection (meaning start equals end) it's probably a good idea to do nothing at all.

window.selWrapBold = function(id) { selWrap(id,'<b>','</b>'); };
window.selWrapItalic = function(id) { selWrap(id,'<i>','</i>'); };
window.selWrap = function(id,startTag,endTag) {
    let elem = document.getElementById(id);
    let start = elem.selectionStart;
    let end = elem.selectionEnd;
    let sel = elem.value.substring(start,end);
    if (sel==='') return;
    let replace = startTag+sel+endTag;
    elem.value =  elem.value.substring(0,start)+replace+elem.value.substring(end);
    elem.select();
    elem.setSelectionRange(start,start+replace.length);
} // end selWrap()
<input type="button" value="bold" onclick="selWrapBold('ta1');"/>
<input type="button" value="italic" onclick="selWrapItalic('ta1');"/>
<br/>
<textarea id="ta1"></textarea>
bgoldst
  • 34,190
  • 6
  • 38
  • 64
0

I used this question to get the selected text. And this question to get the element with selected text in it. I combined them in a single function.

function updateHighlightedText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString(); 
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    var node = $(window.getSelection().anchorNode.parentNode); //Get the selected node
    node.html(node.text().replace(text, "<b>"+text+"</b>")); //Update the node
}
Community
  • 1
  • 1
Deben Oldert
  • 114
  • 1
  • 11