Use Javascript to Highlight Text

Javascript can be used as a handy way to highlight some text for a user when they click on it. This nifty little feature is useful as it saves time for the user since they don't have to do any clicking and dragging.

Use Javascript to highlight text in a textarea

To utilize this feature, we use the javascript onclick event and assign certain actions to it. For example, if we had a textbox with some text in, we would enable automatic highlighting when a user clicked inside of it like so:

<textarea onclick="this.focus();;">
I love Tutorial Arena so much. 
They have the best online web development tutorials.

The result will be what we have below. Go ahead and click inside of it to see for yourself that it works.

The actions we add to the onclick event first make sure that focus is placed on the textbox (think of this as ensuring that the cursor is inside of the textbox), and then highlighting the contents of it.

This is a fairly simple and straightforward use of Javascript to implement some useful behaviour. We hope you learnt something with this Javascript tutorial today.