views:

464

answers:

2

I have some JavaScript code that does two things:

  • retrieves the selected text from a text area
  • adds a prefix and suffix to that selected text

The code currently uses the selectionStart and selectionEnd properties of the textarea to figure out where the selection starts/end, extracts the selection text and processes it, and then re-writes the value of the textarea with the prefix and suffix inserted in the right spots.

This implementation works fine in Firefox but it does not work in Safari. Apparently the selectionStart and selectionEnd properties do not exist in WebKit. (I suspect that the code also does not work in Google Chrome, which is also WebKit-based, though I have not tested this.)

How can I perform these two operations in Safari?

+1  A: 

I believe you're looking for https://developer.mozilla.org/En/DOM:Selection

also appears to work in Safari (not tested by me) (see: http://lists.apple.com/archives/Web-dev/2005/Nov/msg00114.html

Jonathan Fingland
To be honest, I was hoping for something a bit more explicit. eg: exactly how do I replace the selected text? Note also that I only want to do this if the selected text is in a textarea. If random text on the page is selected I'd like to give the user an error instead.
Laurence Gonsalves
A: 

See goog.dom.selection in Closure.

Ben McCann