-1

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.

Community
  • 1
  • 1
heartmo
  • 582
  • 2
  • 6
  • 23

3 Answers3

1

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

Michael
  • 343
  • 2
  • 13
1

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!

heartmo
  • 582
  • 2
  • 6
  • 23
0

use highlight plugin simple

see updated fiddle

and use code

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

    });
Rituraj ratan
  • 10,260
  • 8
  • 34
  • 55
  • 1
    i think he wants to use it for `copy` and your solution wouldn't help – Michael Apr 16 '14 at 12:10
  • Rituraj, thanks for the attempt but Michael is right, I'd like to use the highlighting/selecting to copy the text, not highlight it. – heartmo Apr 17 '14 at 01:01