It's a lot of code, so I don't have the time to write up an answer here right now, but see stackoverflow.com/questions/1592637/… for an idea of how to do it (that example uses jQuery, but only for the event handling -- the text selection stuff is all plain javascript).
If the selection needs to be visible only when the textarea has the focus, you could store the selected start and end, at onblur and at the next onfocus set it again.