Practical Javascript 5: Manipulating Highlighted Text on the Client

In my endless pursuit of all things pragmatic and reusable, I admired this really smart feature that the New York Times site has had for a while. If I visit any article like in this example, I can select a block of text then almost instantaneously a pop-up question mark would appear.

This image happens to be a link that if you click a customized search window would appear:

 

Sound like a job for the client-side. After a few searches, I managed to came up with my own example.

The highlight (no pun intended) of this workflow was capturing the text that has been highlighted.
What follows next (passing the highlighted text to a new window pop-up, etc) is already part of the specific site design itself.

Here is my surprisingly short and simple script:

function CheckSelectedRange() {
  var range = document.selection.createRange();
 
var s = range.htmlText;
   
if (s.length > 0)
     
document.getElementById("highlighted_text").innerHTML = s;
}

What follows next is already the aspx page.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
 
<title>Highlight</title>
 
<script type="text/javascript" language="javascript" src="Highlight.js"></script>
<style type="text/css">
 
.style1{
   
color: #FF3300;
    
font-weight: bold;
   
}
</style>
</head>

<body onmouseup="CheckSelectedRange();">
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
 
<div>
  
<h3>

Even as the industry’s compensation has been put in the spotlight for being so high
at a time when many banks have received taxpayer help, six of the biggest banks       
set aside over $36 billion in the first quarter to pay their employees,            
according to a review of financial statements. If that pace continues all            
year, the money set aside for compensation suggests that workers at many            
banks will see their pay — much of it in bonuses — recover from the lows of last year.
“I just haven’t seen huge changes in the way people are talking about compensation,”
said Sandy Gross, managing partner of Pinetum Partners, a financial recruiting firm. 
 “Wall Street is being realistic. You have to retain your human capital.”
Brad Hintz, an analyst at Sanford C. Bernstein, was more critical. “Like everything on Wall Street,
they’re starting to sin again,” he said. “As you see a recovery, you’ll see
everybody’s compensation beginning to rise.”
</h3>
</div>
  
<br />
    
<p class="style1">SELECTED TEXT:</p>
         <asp:Label ID="highlighted_text" runat="server"
           
style="font-family: 'Courier New', Courier, monospace; font-size: small; color: #3333CC" />
</form>
</body>
</html>

Hope you all enjoy.

Attachment: Highlight.zip
Published 04-26-2009 3:42 PM by avcajipe
Filed under: ,