jquery - Selecting Text through JavaScript -
i want select text thats on html page , make bold, using following code
<script type="text/javascript" > function getselectedtext(){ if(window.getselection){ ; return window.getselection().tostring(); } else if(document.getselection){; return document.getselection(); } else if(document.selection){ ; return document.selection.createrange().text; } } $(document).ready(function(){ $("*").live("mouseup", function() { selection = getselectedtext(); alert(selection); if(selection.length >= 3) { $(this).html($(this).html().replace(selection, "<b>" + selection + "</b>") ); } } ); }); </script>
this code works fine when text in 2 different paragraphs/ div or if there link between text doesnt seem work.
how make work ?
if want kind of highlighting of current selection, using built-in document.execcommand()
easiest way. works in major browsers.
the following should want on selection, including ones spanning multiple elements. in non-ie browsers turns on designmode
, applies background colour , switches designmode
off again.
update
fixed work in ie 9.
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 browsers apply backcolor whole block if (!document.execcommand("hilitecolor", false, colour)) { document.execcommand("backcolor", false, colour); } document.designmode = "off"; } function highlightselection(colour) { var range; if (window.getselection) { // ie9 , 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); } } document.onmouseup = function() { highlightselection("red"); };
live example: http://jsfiddle.net/ebqbu/9/
Comments
Post a Comment