Apr 2nd
2009

Highlight Selected Text with jQuery

I had a need to take some selected text, and highlight it.  I thought it would be a simple job for jQuery, and a good way for me to learn it, now that I’ve decided to make the switch from Prototype/Scriptaculous to jQuery.  (More on that later)

The code example below does a few simple things.  It takes any user-selected text that is in a <p> tag and wraps it in <span> tags and gives that span a class of “hl”.  Then, my CSS just has a simple rule:

span.hl { background: yellow; }

I’m using the live() method here so that the changes that I make are immediately available in the browser.  Finally, if there is another action  you’d like to take after text has been selected, I added a simple alert() to the script.

I’m sure there are other/better ways to do this, but this worked for my current needs.  Please feel free to expand upon it, I’d love to see more optimal ways of doing this.

//Wrap selected text in  tags with the class 'hl'
//Take some action after (in this case, a simple alert)
$("p").live("mouseup",
	function() {
	   	selection = getSelectedText(); 
		if(selection.length >= 3) {
			$(this).html($(this).html().replace(selection, $('<\/span>').attr({'class':'hl'}).html(selection).parent().html()) );
			alert(selection);
		}		
	}
); 

//Grab selected text
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; 
    } 
} 
Next Post → ← Previous Post