Highlight The Contents Of A Textarea With JavaScript

27th August 2008 - 1 minute read time

If you want to give your users a little snippet of code it is nice to give them the option of selecting the entire block of code without having to highlight the text manually. This can be done with a simple JavaScript button.

Take the following form:

  1. <form name="aForm">
  2. <textarea name="aTextarea" cols="50" rows="20">
  3. Copy this text onto your own website.
  4. </textarea>
  5. </form>

To enable the selection functionality you just need to add in an input button. The click event of this button will be to run a JavaScript bookmarklet that focuses on the textarea in question (in this case it is called aTextarea) and selects the text.

  1. <form name="aForm">
  2. <textarea name="aTextarea" cols="50" rows="20">
  3. Copy this text onto your own website.
  4. </textarea>
  5. <br />
  6. <input type="button" value="Highlight All" onclick="javascript:this.form.aTextarea.focus();this.form.aTextarea.select();" />
  7. </form>

The user can then copy the text as they normally would.

Add new comment

The content of this field is kept private and will not be shown publicly.