15.02.2013 Views

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

getSelection()<br />

Chapter 4 ✦ The Document and Body Objects (Chapter 18)<br />

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5<br />

Compatibility ✓ ✓<br />

Example<br />

The document in Listing 18-15 provides a cross-browser (but not IE5/Mac) solution<br />

to capturing text that a user selects in the page. Selected text is displayed in<br />

the textarea. The script uses browser detection and branching to accommodate the<br />

diverse ways of recognizing the event and reading the selected text.<br />

Listing 18-15: Capturing a Text Selection<br />

<br />

<br />

Getting Selected Text<br />

<br />

var isNav4 = (navigator.appName == “Netscape”<br />

&& parseInt(navigator.appVersion) == 4)<br />

var isNav4Min = (navigator.appName == “Netscape” &&<br />

parseInt(navigator.appVersion) >= 4)<br />

var isIE4Min = (navigator.appName.indexOf(“Microsoft”) != -1 &&<br />

parseInt(navigator.appVersion) >= 4)<br />

function showSelection() {<br />

if (isNav4Min) {<br />

document.forms[0].selectedText.value = document.getSelection()<br />

} else if (isIE4Min) {<br />

if (document.selection) {<br />

document.forms[0].selectedText.value =<br />

document.selection.createRange().text<br />

event.cancelBubble = true<br />

}<br />

}<br />

}<br />

if (isNav4) {<br />

document.captureEvents(Event.MOUSEUP)<br />

}<br />

document.onmouseup = showSelection<br />

<br />

<br />

<br />

Getting Selected Text<br />

<br />

Select some text and see how <strong>JavaScript</strong> can capture the selection:<br />

ARTICLE I<br />

<br />

Continued<br />

251<br />

document.getSelection()

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!