Question

I am trying to select/highlight text (like what would happen if you click+drag your mouse across some text) across multiple ranges.

Here is a fiddle that demonstrate's what I'd like to do but am unable to http://jsfiddle.net/KcX6A/2816/

I tried adding SelectText("selectme2"); to the JQuery but then it deselects the first div.

I got this method from here Selecting text in an element (akin to highlighting with your mouse) but it only selects a single range.

Was it helpful?

Solution

Try it this way, somehow it works fine in Firefox but not in Chrome, maybe a browser compatibility issue..

HTML -

<div class="selectme">Some text to highlight</div>
<div> Don't select this </div>
<div class="selectme">Select this text too.</div>
<br>
<p>Click me!</p>

Javascript-

function SelectText(element) {
    var strongs = document.getElementsByClassName(element);
    var s = window.getSelection();
    if(s.rangeCount > 2) s.removeAllRanges();

    for(var i = 0; i < strongs.length; i++) {
         var range = document.createRange();
         range.selectNode(strongs[i]);
         s.addRange(range);
    }
}

$(document).ready(function(){
    $('p').click(function() {
        myClass="selectme";
       SelectText(myClass);   
    });
});

And here is a live JSfiddle example

OTHER TIPS

It turns out this is still impossible in all of the major browsers except for firefox after digging around some more. Here's 1 source http://lists.whatwg.org/htdig.cgi/whatwg-whatwg.org/2011-January/030102.html

Thanks for the help though!

use highlight plugin simple

see updated fiddle

and use code

$('p').click(function() {
       $("div").highlight("highlight");

    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top