2

We have a HTML page. Is it possible to select (by mouse) few words of a paragraph, get reference to those selected words and encapsulate them, say, by the <span>...</span> tag programatically? We can use jQuery or HTML5/CSS3?

Cartesius00
  • 23,584
  • 43
  • 124
  • 195

2 Answers2

3

You can use a mouseup handler and use getSelection. Say you have a div called testtagging, then this is a way to add a span to a selected text within that div. See this jsfiddle.

$('#testtagging').on('mouseup',tag);

function tag(e){
    tagSelection('<span style="color:red">$1</span>');
}

function tagSelection(html) {
    var range, node;
    if (document.selection && document.selection.createRange) {
     //IE
     range = document.selection.createRange();
     range.pasteHTML(html.replace(/\$1/,range.text));
     return true;
    }
    if (window.getSelection && window.getSelection().getRangeAt) { 
     //other browsers
     range = window.getSelection().getRangeAt(0);
     node = range.createContextualFragment(
                  html.replace(/\$1/,range.toString())
            );
     range.deleteContents();     
     range.insertNode(node);
    } 
    return true;
}​

[edit] adjusted for use with IE too. JsFiddle is also adapted

KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

JSFiddle working example

Propose to wrap all paragraph words into span elements:

var r = /(\S+)/ig;
var text = $("p").text();
$("p").html(text.replace(r, "<span class='w'>$1</span>"));

Then bind hover/click events:

$("p > .w").on("hover", function()
{
    $(this).toggleClass("hover");
})
.on("click", function()
{
    $(this).toggleClass("selected");
});

If you want to parse words from selected text range, you should use window.getSelection().

Refer to this question or ask me to adapt this code.

Community
  • 1
  • 1
fedosov
  • 1,989
  • 15
  • 26