Getting Selected Text


You can access text the user selected with the mouse in a web page, but the technique you use differs by browser. In the Netscape Navigator, you can use the document.getSelection method; in the Internet Explorer, however, you use the document.selection property, then create a text range from that property using the createRange method, and use the text range's text property to find the selected text. Here's an example, designed for Internet Explorer 6.0 and Netscape Navigator 6.0; this example displays the text the user has selected as soon as the user releases the mouse button:

(Listing 09-07.html on the web site)
 <HTML>      <HEAD>          <TITLE>Reading Selected Text</TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function getSelected()   {   if (navigator.appName == "Microsoft Internet Explorer") {   document.form1.text1.value = document.selection.createRange().text   }   if(navigator.appName == "Netscape") {   document.form1.text1.value = document.getSelection()   }   }  // -->          </SCRIPT>      </HEAD>      <BODY ONMOUSEUP="getSelected()">          <H1>Reading Selected Text</H1>          Select some of this text!          <BR>          <FORM NAME="form1">              You selected: <INPUT TYPE="TEXT" NAME="text1">          </FORM>      </BODY>  </HTML> 

You can see the results in Figure 9.4, where I'm selecting some text and the code is displaying it.

Figure 9.4. Setting and retrieving selected text.

graphics/09fig04.gif

Tip

Although I've used the document.getSelection method here because this chapter is on the document object, Netscape now looks down on that method, considering it deprecated , which means it will eventually stop being supported. The method that is replacing document.getSelection is window.getSelection (covered in Chapter 8, "Using Window and Frame Methods and Events").




Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net