Sunday, December 27, 2009

JQuery Script to Display the Currently Selected Text in a Web Page

I needed to demonstrate the ability to detect and use the selected text in a web page.  It was surprising difficult to find a simple example to do this.

The code displays the currently selected text in a web page when either an uppercase or lowercase Q is pressed. It uses JQuery 1.3.2. I have tested it in Internet Explorer 8 and Firefox 3.5.6.

<script src="/Scripts/jquery-1.3.2.min.js" 
type="text/javascript"></script>
<
script type="text/javascript">
$(document).keypress(function(e) {
// alert("Key Pressed of " + e.which);
if (e.which == 81 || e.which==113) { // Q=81, q=113
// Get the selected text
var selected_text;
if (document.getSelection) {
selected_text = document.getSelection();
}
else if (document.selection.createRange) {
var range = document.selection.createRange();
selected_text = range.text;
}
else {
selected_text = "";
}

// Show the selected text to the user
if (selected_text != "") {
alert("Selected Text = '" + selected_text + "'");
}
else {
alert("No text selected");
}
}
return false;
});
</script>



Hope that helps.

Joe Kunk

Microsoft MVP

Okemos, MI USA

12-27-2009

No comments: