3

I am pretty new to JQuery. I have a text in a div. When the user double clicks a word, I want to select all word's appearances. The problem is that I don't know how to refer to the selected word. Can anybody help me? Thanks in advance

NakedBrunch
  • 48,713
  • 13
  • 73
  • 98
lama
  • 39
  • 1
  • 4

4 Answers4

4

This seems to work: http://jsfiddle.net/f3wzT/

The code finds the double-clicked word and then wraps all instances of the word in a span. There might be a better way to do it but, as you can see from the jsFiddle above, this does work.

Here's the code (quickly cobbled together from multiple sources):

<script type="text/javascript">
    function getSelectedText() {
        var txt = '';
        if (window.getSelection) {
            txt = window.getSelection();
        } else if (document.getSelection) {
            txt = document.getSelection();
        } else if (document.selection) {
            txt = document.selection.createRange().text;
        }
        return txt;
    }

    function deselectText() {
        if (window.getSelection) {
            window.getSelection().removeAllRanges();
        } else if (document.getSelection) {
            txt = document.getSelection().removeAllRanges();
        } else if (document.selection) {
            txt = document.selection.empty;
        }

    }

$(document).ready(function() {  
    $('#content').dblclick(function() {
        $('.highlight').removeClass('highlight');
        var t = getSelectedText();
        var regex = new RegExp(t, "gi");
        this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"highlight \">" + matched + "</span>";});
        deselectText();
    });

});
</script>
NakedBrunch
  • 48,713
  • 13
  • 73
  • 98
1

Try this:

http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html

mbx-mbx
  • 1,765
  • 11
  • 23
0

There is a previous answer to this on stack that can be adapted from using paragraph to div.

Here

You can change the alert to find the text in other places in the document and highlight them.

Community
  • 1
  • 1
Laurence Burke
  • 2,348
  • 14
  • 26
0

Here is a sample that puts a span around each word and then highlights all spans that have the same text. http://jsfiddle.net/6xsNK/3/

$('.para').each(function() {
    var words = $(this).text().split(' ');
    var el = $(this).empty();
    $(words).each(function(i) {
        el.append($('<span>').text(this+' '));
    });
});

$('.para span').dblclick(function() {
    var t = $(this).text();
    var count = $('.para span').removeClass('hilite').filter(function() { return $(this).text() == t;}).addClass('hilite').size();
    alert(count+' match(es) found');
});
js1568
  • 7,012
  • 2
  • 27
  • 47