This recipe will teach you how to retrieve the text that is selected by a user and perform some basic formatting on it.
On click of a button, we first get the start and end positions of selected text using the ge
tPositions()
function. Determining this value is a bit complex as different browsers have different methods for handling selections. Internet Explorer uses document.selection
, which represents a subset of documents, whereas Mozilla and similar browsers use window.getSelection
.
IE has a range of objects using which we can determine what text was selected, and the start and end positions of selection in original text. First we create a range object from the selection. Then we create a clone of it using the duplicate
method. After this, two functions moveToElementText()
and setEndPoint()
are used on the duplicated range. These methods align the values of original text and the selection.
Once this is done, we compare the values of the original and the duplicated range to find out the start position. Then we add the length of the selection to the start position, which gives us the end position marker.
For other browsers, getting positions is relatively simple. Start and end positions of selections in textarea can be retrieved using .selectionStart
and .selectionEnd
properties.
Once we get both these values, we create an object in which we put both of these and return the object to the calling function.
If the values of both these positions are equal, it means that no text is selected. In this case we simply return from the function and do nothing.
Then we determine which button was clicked. The clicked button's value will be used to format the selected text. After that, we store the value of textarea in a local variable textOnPage
.
Now comes the part where the actual manipulation takes place. We break the textOnPage
variable into three parts. The first part contains the string from the beginning to the starting position of the selection. The second part of the string is the actual selected text of textarea that has to be formatted. We now enclose it in HTML tags (<b>
, <i>
, or <u>
) according to the button clicked. The third and final part is from where the selection ends to the end of the string.
To get the resulting string we can now simply concatenate these three strings and place it back into the textarea. The textarea will now have text that has the selected text enclosed in HTML tags. To verify this, click on the Apply HTML button. This will take the text from the textarea and insert it as HTML into the paragraph with ID container
.