Home › Forums › JavaScript › Detect selected text › Re: Detect selected text
Here is what you are looking for…
// Get user selection text on page function getSelectedText() { if (window.getSelection) { return window.getSelection(); } else if (document.selection) { return document.selection.createRange().text; } return ''; }
$(document).ready(function(){ $("#button").click(function(){ var myObj = $('#highlight');//change to the location of the text you want selected/highlight-able myObj.html( myObj.html().replace(getSelectedText(),''+getSelectedText()+'') );//notice class name "selected" }); });
Highlight any part of this text then click the button to make it selected.
Now the only problem is you can’t overlap your highlight with my script, because the getSelectedText only returns text, not also html. I’m working on a fix for that. Enjoy