Nico Schlömer
Nico Schlömer

Reputation: 58841

Dynamically update selected text in particular HTML element

I'm trying to dynamically update a text selection in a particular HTML element. To this end, the link function contains

element.on('mouseup', function(event) {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }

(Partly taken from https://stackoverflow.com/a/5379408/353337). This works well when clicking around and selecting text within element.

The problem with this is that the mouseup event is only intercepted on the particular element. If I click anywhere else on the page, the text in the element is deselected as well, of course, but the event never fires.

How can I make sure that text always contains the selected text in element?

Upvotes: 0

Views: 127

Answers (1)

lehnerchristian
lehnerchristian

Reputation: 1267

I think you have to listen on the whole document for the event. JSFiddle

To check if the marked word is part of the word (or the same) I used the indexOf function, which returns 0 if the word is equal or 1 if it is part of the word. So I compared to greater or equal 0.

$(document).on('mouseup', function (e){
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }

    var elementText = $(".element").text();

    if(elementText.indexOf(text) >= 0) {
        alert(true);    
    }
    else {
        alert(false)
    }
});

Upvotes: 1

Related Questions