PDA

View Full Version : getSelection in Mozilla


Mr J
09-13-2004, 10:47 AM
When using the following;

In Mozilla:

if I press the Moz button I get the text that I select but if I press the Script button I get "undefined"

In IE:

if I press the IE button I get "[object]" but the script shows the selected text

Can someone educate me here please

Thank you


<HTML>
<HEAD>
<TITLE>Document Title</TITLE>
<SCRIPT>
<!--
moz=document.getElementById&&!document.all
function ShowSelection(){
if(!moz){
oTextRange = document.selection.createRange(); // works in IE
}
else{
oTextRange = window.getSelection() // no work in Moz
}

alert("You highlighted the following text:\n\n"+oTextRange.text);
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<center>
<form>
<input type="button" value="Moz" onClick="alert(window.getSelection())"> works in Moz<BR>
<input type="button" value="IE" onClick="alert(document.selection.createRange())"> no work in IE
<BR><BR>
<input type="button" value="Script" onClick="ShowSelection()"> no work in Moz, works in IE
</form>

<P>Select all or part of this text</P>

</center>
</BODY>
</HTML>

jbot
09-13-2004, 10:51 AM
<input type="button" value="Script" onClick="ShowSelection()"


dunno if that's a typo, but you never closed your tag. also, close your paragraph tags, otherwise your markup doesn't validate. furthermore, all preceeding nodes become children of that one.

Mr J
09-13-2004, 11:41 AM
I corrected my typos in my previous post. :o

Still does not work as explained :(

jbot
09-13-2004, 11:56 AM
in Mozilla, it's because text is prolly not a property of getSelection. instead, use toString(). see here (http://www.mozilla.org/docs/dom/domref/dom_window_ref24.html) for details.

Mr J
09-13-2004, 12:51 PM
jbot.

Thanks for the guidance there. :thumbsup:

I'd already been to that page and it is quite clear to me now that both my braincells were obviously not working together. :eek:

Now that I have them in check here is the final result :D


<HTML>
<HEAD>
<TITLE>Document Title</TITLE>
<SCRIPT>
<!--
moz=document.getElementById&&!document.all
function ShowSelection(){
oTextRange = (!moz?document.selection.createRange():window.getSelection())
oTextRange = (!moz?oTextRange.text:oTextRange.toString())

alert("You highlighted the following text:\n\n"+oTextRange);

}
// -->
</SCRIPT>
</HEAD>
<BODY>
<center>
<form>
<input type="button" value="Moz" onClick="alert(window.getSelection())"><BR>
<input type="button" value="IE" onClick="alert(document.selection.createRange().text)">
<BR><BR>
<input type="button" value="Script" onClick="ShowSelection()">
</form>
<P>Select all or part of this text</P>
</center>
</BODY>
</HTML>


Although the .toString() is not really needed in this instance