I needed to do something similar recently.
Firstly, you cannot have two different elements selected at the same time. Therefore, for this you will need to imitate the built-in “highlighted text selection” of the browser. To do this, you will need to insert spaces in the text to simulate the selection, and then capture the mousedown and mouseup events.
Here's the StackOverflow user script " fullpipe " that illustrates the technique I used.
http://jsfiddle.net/fullpipe/DpP7w/light/
$(document).ready(function() { var keylist = "abcdefghijklmnopqrstuvwxyz123456789"; function randWord(length) { var temp = ''; for (var i=0; i < length; i++) temp += keylist.charAt(Math.floor(Math.random()*keylist.length)); return temp; } for(var i = 0; i < 500; i++) { var len = Math.round(Math.random() * 5 + 3); document.body.innerHTML += '<span id="'+ i +'">' + randWord(len) + '</span> '; } var start = null; var end = null; $('body').on('mousedown', function(event) { start = null; end = null; $('span.s').removeClass('s'); start = $(event.target); start.addClass('s'); }); $('body').on('mouseup', function(event) { end = $(event.target); end.addClass('s'); if(start && end) { var between = getAllBetween(start,end); for(var i=0, len=between.length; i<len;i++) between[i].addClass('s'); alert('You select ' + (len) + ' words'); } }); }); function getAllBetween(firstEl,lastEl) { var firstIdx = $('span').index($(firstEl)); var lastIdx = $('span').index($(lastEl)); if(lastIdx == firstIdx) return [$(firstEl)]; if(lastIdx > firstIdx) { var firstElement = $(firstEl); var lastElement = $(lastEl); } else { var lastElement = $(firstEl); var firstElement = $(lastEl); } var collection = new Array(); collection.push(firstElement); firstElement.nextAll().each(function(){ var siblingID = $(this).attr("id"); if (siblingID != $(lastElement).attr("id")) { collection.push($(this)); } else { return false; } }); collection.push(lastElement); return collection; }
As you can see in the violin, the gibberish text in the right pane remains highlighted regardless of focus elsewhere on the page.
At this point, you will have to apply color changes to all relevant ranges.
source share