I'm working on a BBcode editor, and was wondering how to toggle tags on selection using Javascript (similar to how the text editing menu works on StackOverflow).
Example:
Textarea
Lorem ipsum dolor sit amet.
If you select the text 'ipsum dolor' and click on the bold button, it'll become
Lorem [b]ipsum dolor[/b] sit amet.
If you click the bold button once again, it'll remove the tags.
Thanks!
You can get the selected text caret positions, set the caret and then insert your text:
TL;DS (Too long didn't scroll)
There's a TL;DR at the bottom.
Get Caret Positions
Set Caret Position
Insert Text
Do Your Inserting
Then to undo it, just check the text selection when they click the button, and if its wrapped in the thing you clicked (eg [b]...[/b], when clicking the B button) then just remove that text from the textbox selection.
TL;DR
Get a markdown plugin instead http://markitup.jaysalvat.com/home/
or look at these http://www.queness.com/post/212/10-jquery-and-non-jquery-javascript-rich-text-editors