Javascript Quandary: creating a marker pen tool ... almost there

I am working on a small JS plugin that I want to work just like a real marker. Take the standard div of html-text (with children), select the text with the mouse and leave the selection intact on the mouse up. Seems pretty straight forward, right?

Here is what I still have: http://efflux.us/text/views/select.php (the window on the right displays your selection for testing purposes)

So, if you select a few words of text, everything will be fine. Try to select several groups of words and you will notice css background changes. However, I have two egregious problems ...

1) Selecting multiple lines of text does not work. When selecting multiple lines, the getSelection () function does not capture the <br /> tags, which are necessary to match the line inside the main container <div class='text> . These <br /> tags are critical to the application I'm building, so they are definitely necessary. When you delete them, you can select multiple lines.

2) When you select a common word or phrase, each instance of this object is highlighted. I would like the selected text to be highlighted, but can't figure it out. Try choosing the very first word "The" ... you will see what happens.

Side notes .. I'm based on the highlight function from the Johann Burkard plugin, but I can’t think of a way to further modify the script. I am ready to write something new, but my brains are sorted out to understand this.

Any help would be appreciated!

+4
source share
1 answer

Actually, it is quite simple using document.execCommand() . This is a little complicated because you need to temporarily make the document editable in a browser other than IE for document.execCommand() to work, which in turn destroys the selection in some browsers, but it is easy enough to work with. It works in all major browsers, including IE 6.

UPDATE: fixed for IE 9.

jsFiddle: http://jsfiddle.net/timdown/Hp7Zs/32/

code:

 function makeEditableAndHighlight(colour) { var range, sel = window.getSelection(); if (sel.rangeCount && sel.getRangeAt) { range = sel.getRangeAt(0); } document.designMode = "on"; if (range) { sel.removeAllRanges(); sel.addRange(range); } // Use HiliteColor since some browsers apply BackColor to the whole block if (!document.execCommand("HiliteColor", false, colour)) { document.execCommand("BackColor", false, colour); } document.designMode = "off"; } function highlightSelection(colour) { var range, sel; if (window.getSelection) { // IE9 and non-IE try { if (!document.execCommand("BackColor", false, colour)) { makeEditableAndHighlight(colour); } } catch (ex) { makeEditableAndHighlight(colour) } } else if (document.selection && document.selection.createRange) { // IE <= 8 case range = document.selection.createRange(); range.execCommand("BackColor", false, colour); } } 
+4
source

All Articles