• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

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> 

					  


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint