Cartesius00
Cartesius00

Reputation: 24384

Tag few words from text

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?

Upvotes: 2

Views: 187

Answers (2)

KooiInc
KooiInc

Reputation: 122936

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

Upvotes: 3

fedosov
fedosov

Reputation: 2049

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.

Upvotes: 0

Related Questions