NYCPHP Meetup

NYPHP.org

[nycphp-talk] Javascript Highlighter

Greg Rundlett greg.rundlett at gmail.com
Thu Jun 19 00:38:22 EDT 2008


On Mon, Jun 16, 2008 at 1:41 PM, Aniesh joseph <anieshjoseph at gmail.com> wrote:
> Hi All,
>
> I wish to create a Javascript Highlighter. While we are reading some texts
> on a webpage, I need to select certain words or paragraphs. When I click on
> the selected portion, it need to remain as unselected. When we move to next
> page, no need to keep this selection.
>
> Any ideas would be great!
>
> Thank you all.

You are talking about manipulating text selection ranges.  I didn't find an
off-the-shelf complete solution, but found several useful sources to help
you.

http://www.quirksmode.org/dom/range_intro.html

/**
 * This code is a derivative work of Moodle
 * and is licensed under the GPL-v2
 */
function getSel(){
  var seltext;
  if (window.getSelection)
    seltext=window.getSelection();
  else if (window.document.getSelection)
    seltext=window.document.getSelection();
  else if (window.document.selection)
    seltext=window.document.selection.createRange().text;
  return seltext;
}
seltext = '';
if(window.frames.length == 0){ // Can't read from another frame, JS security
  seltext=getSel();
}
if(seltext!='') {
  // create a new element at the point of click, wrapping the selection
document.selection.createRange().pasteHTML("<span style='background-color:
yellow;'>" + seltext + "</span>");
  // problem is that pasteHTML is for IE only
  // I didn't have a chance to work out a full solution or test this code
}


This older solution may help you achieve cross-platform compatibility with
older browsers
http://www.faqts.com/knowledge_base/view.phtml/aid/32427

This hack may be useful http://www.codingforums.com/showthread.php?t=62782

-- Greg Rundlett
http://freephile.openid.org



More information about the talk mailing list