Click to Select
The content within HTML container elements (like div
, pre
, p
, and td
) can be made selectable with a click or a tap. To do so, JavaScript is required.
When content is selected, the website user can do what they want with it. Generally, they would copy the selected content for pasting somewhere else. (Selecting content does not automatically copy the content.)
Keep in mind that this selection feature may not work in most email readers, as they typically do not support JavaScript.
Here is an example of a container element, specifically a paragraph (p
tag).
This paragraph is an example of content that may be selected when tapped. When you tap the text, JavaScript causes the text to be selected. When you tap anywhere else, the browser will automatically deselect the text.
To enable an HTML container element to have its content selected, such as a p
tag like the above example, first put this JavaScript anywhere in the web page.
<script type="text/javascript"> function containerSelect(id) { if(document.selection) { var range = document.body.createTextRange(); range.moveToElementText(id); range.select(); } else if(window.getSelection) { var range = document.createRange(); range.selectNode(id); window.getSelection().addRange(range); } } </script>
Then, put this attribute into the p
tag (or other HTML container element). Once the above JavaScript is in the web page source code, this attribute may be put into the tag of as many HTML container elements as you want.
onclick="containerSelect(this)"
For reference, here is the complete source code for the example paragraph.
<p onclick="containerSelect(this)" style="border:3px dotted black; padding:1em; border-radius:1em;">
This paragraph is an example of content that may be selected when tapped. When you tap the text, JavaScript causes the text to be selected. When you tap anywhere else, the browser will automatically deselect the text.
</p>
It is fairly simple to implement tap-to-select functionality.
-
Ensure the JavaScript is on the web page.
-
Insert the
onclick="containerSelect(this)"
attribute into every tag that shall have click-selectable text.
For additional examples of use, see the copiable code in most Possibilities articles. The code is generally in click-to-select pre
tags.
(This content first appeared in Possibilities newsletter.)
Will Bontrager