[thelist] Using Javascript to add tags to selected text in textarea

Simon Willison simon at incutio.com
Fri May 24 09:55:00 CDT 2002


At 15:35 24/05/02 +0100, I wrote:
I think I'll have to give up on the Mozilla implementation. It seems that
>Mozilla has a document.getSelection() method which can grab the selected
>text but there is no equivalent to Microsoft's textrange object through
>which you can manipulate the currently selected area.

Looks like I spoke too soon. I've just discovered that the object returned
by document.getSelection() in Mozilla is a "Selection" object which can be
further manipulated. Documentation on this page:

http://www.pbwizard.com/Articles/Moz_Range_Object_Article.htm

My problem now is that if I select some text in a text box and then click
on a button outside the text box in Mozilla the text is unselected (due to
my selection of the button). This is preventing me from running the code to
process the selection as the act of hitting the button cancels the
selection I want to use :(

The code I am playing with at the moment is as follows:

<html>
<body>
<script type="text/javascript">
function doit() {
   theSelection = document.getSelection();
   if (!theSelection)
     return false;
   alert(theSelection);
   alert(theSelection.anchorNode);
}
</script>
<form>
<textarea rows=5 cols=40></textarea>
<input type="button" onClick="doit()" value="hi" />
</body>
</html>

<tip type="Client side code testing" author="Simon Willison">
If you want to do a quick experiment with HTML, CSS or JavaScript without
having to create a whole new HTML document head over to www.w3schools.com
and use their "Try it" feature - this provides you with a textarea to enter
HTML on the right and a frame where the code you have entered will be
displayed on the right. It's a great tool for trying things in a hurry.
Direct link:

http://www.w3schools.com/html/tryit.asp?filename=tryhtml_headers
</tip>




More information about the thelist mailing list