Tap to Select
Allowing site visitors to select content with a tap can be a sign of caring. That's especially true for content they are likely to want to copy, like source code to reuse or a list of requirements for something.
I'll describe how to implement the functionality.
The first step to implement the functionality is to put this JavaScript somewhere on the web page. No customization is required. The JavaScript can be anywhere that it's convenient. Placing it near the bottom of the page, above the cancel </body>
tag is good.
<script type="text/javascript"> function SelectContent(d) { if(document.selection) { document.selection.empty(); // First, unselect any already selected. var range = document.body.createTextRange(); range.moveToElementText(d); range.select(); } else if(window.getSelection) { window.getSelection().removeAllRanges(); // First, unselect any already selected. var range = document.createRange(); range.selectNode(d); window.getSelection().addRange(range); } } </script>
With the JavaScript in place, you are now ready to provide tap-to-select ease to your site visitors.
The content within any HTML content container can be selected with a tap — except form fields, which use a different mechanism for one‑tap selection. There are three ways: Tapping the content within the container, tapping a link to select, or tapping a button to select.
Each of the following examples contains the example and then the source code.
Tap Content Within Container
The div is not required to have an id value to use this method.
<div onclick="SelectContent(this)" style="max-width:2in; border:1px dashed black; padding:.5em;">
Tap on the content of this div to select the content.
</div>
Tap a Link
The div must have an id value to use this method. To implement, the link code can be anywhere on the web page.
Tap me<a href="javascript:SelectContent(document.getElementById('a-link-demo'))">Tap me</a> <div id="a-link-demo" style="max-width:2in; border:1px dashed black; padding:.5em;"> Tap the "Tap me" link (above this div) to select this content. </div>
Tap a Button
The div must have an id value to use this method. To implement, the button code can be anywhere on the web page.
<input type="button" onclick="SelectContent(document.getElementById('a-button-demo'))" value="Tap me" style="width:fit-content;"> <div id="a-button-demo" style="max-width:2in; border:1px dashed black; padding:.5em;"> Tap the "Tap me" button (above this div) to select this content. </div>
Making it easy for your site visitors to select content they probably will want to copy is a gesture of friendliness.
(This content first appeared in Possibilities newsletter.)
Will Bontrager