Displaying user selected text
You must have seen the WYSIWYG (What You See Is What You Get) editors in web applications, which allow you to select some text using the mouse or keyboard and then format it (like making it bold, changing its color, and so on).
This recipe will teach you how to retrieve the text that is selected by a user and perform some basic formatting on it.
Getting ready
Get the jQuery library ready.
How to do it...
Create a file named
textSelect.html
in yourchapter1
directory.Create four buttons out of which the first three will be used to make the text bold, italic, and underlined respectively. Then create a textarea with some text in it. And finally, enter a paragraph that will be used to display the formatted HTML.
The last button will get the value of textarea and will insert it in the paragraph.
<html> <head> <title>Manipulating user selected text</title> <style type="text/css"> p { color:red;font-size:17px;width:670px;} </style> </head> <body> <input type="button" value="b" id="bold" class="button"> <input type="button" value="i" id="italics" class="button"> <input type="button" value="u" id="underline" class="button"> <input type="button" id="apply" value="Apply HTML"> <div> <textarea id="selectable" rows="20" cols="80">I consider thata man's brain originally is like a little empty attic, and you have to stock it with such furniture as you choose. A fool takes in all the lumber of every sort that he comes cross, so that the knowledge which might be useful to him gets crowded out, or at best is jumbled up with a lot of other things, so that he has a difficulty in laying his hands upon it.</textarea> </div> <p id="container"></p> </body> </html>
Include the jQuery library and write the JavaScript function that will get the start and end positions of the selected text.
<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> function getPositions() { var startPosition = endPosition = 0; var element = document.getElementById('selectable'); if (document.selection) { //for Internet Explorer var range = document.selection.createRange(); var drange = range.duplicate(); drange.moveToElementText(element); drange.setEndPoint("EndToEnd", range); startPosition = drange.text.length - range.text.length; endPosition = startPosition + range.text.length; } else if (window.getSelection) { //For Firefox, Chrome, Safari etc startPosition = element.selectionStart; endPosition = element.selectionEnd; } return {'start': startPosition, 'end': endPosition}; }
Next, write the code for the Apply HTML button that will simply get the text from the textarea and insert it in the paragraph.
$('#apply').click(function() { var html = $('#container').html($('#selectable').val()); });
Let's code the first three buttons now. We will bind the click event with the three buttons. On the click of each button, the position of the selected text will be retrieved and it will be enclosed within HTML tags depending on which button is clicked.
$('.button').click(function() { var positions = getPositions(); if(positions.start == positions.end) { return false; } var tag = $(this).val(); var textOnPage = $('#selectable').val(); var startString = textOnPage.substr(0, positions.start); var targetString = textOnPage.substr(positions.start, positions.end - positions.start); var formattedString = "<" + tag +">" + targetString + "</" + tag +">"; var endString = textOnPage.substr(positions.end); $('#selectable').text(startString + formattedString + endString); });
Save the code, start your browser and point it to the file. Select some text with your mouse and click on any of the buttons. You will see that the selected text has been enclosed with the corresponding HTML tags. If you click on the second button (u), the selected text will be enclosed in
<u>
and</u>
HTML tags.Now click on the Apply HTML button. You will be able to see the formatted text of the textarea in HTML format inside the paragraph, as seen in the following screenshot:
How it works...
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
.
There's more...
Short method for getting selected text
Another method can be used to get the selected text from other elements, such as <div>
, <p>
, and so on. This will not give any positions but simply the selected text. Note that this method will not work for textareas for Mozilla and similar browsers but it will work in Internet Explorer for textareas as well as other controls.
Use the following function to get the selected text:
function getSelectedText() { var selectedText = ''; if (document.selection) { var range = document.selection.createRange(); selectedText = range.text; } else if (window.getSelection) { selectedText = window.getSelection(); } return selectedText; }