2 min read
·
By Dag Frode Solberg
·
December 5, 2019
When creating a website, you are trying to solve some real-world problems. People don't come to your site to look at the website. There might be exciting content or important information they need. Often the information they need is copied into some other application.
The following table contains some cells that are easy to copy, and some that are a bit harder to copy.
For the next few minutes, we will explore how we can make all the cells with data easy to copy for most of the browsers in use today!
By adding some CSS to the table, we can make all the text in the cells are selectable by a single click. This solution currently works for Firefox and Chrome.
The CSS we have added to the table is:
table {
user-select: all;
}
When you click on some content in an element with the style user-select: all;
, the browser knows it should treat all the content as one atom. This styling lets the user click anywhere in the element and get all of the text selected.
Let us see how this works in practice:
When you click on any of the content in cells, all of the cells are selected. But we do not communicate this to the users at this point. We need some way to let the user know in advance what is going to happen when they click on the text. By adding the style cursor: cell;
to the cell, we let the user know the content of the cell can be selected.
table td {
user-select: all;
cursor: cell;
}
We now have a solution that lets Chrome and Firefox users understand that they can select the content of a cell, but we want to support the rest of the internet too.
First, we add a class to the elements we want to be possible to select by only clicking on the element.
<td class="user-select-all"></td>
Then we add the following polyfill to be loaded at the end of our document.
// based on https://stackoverflow.com/a/20079910
//Supports IE9+
function userSelectAll(event) {
window.getSelection().selectAllChildren(event.target);
}
// Use CSS.suports to only run polyfill for browsers not supporting the property
if (!CSS || CSS.suports || !CSS.supports("user-select", "all")) {
var elementsToSelectOnClick = document.querySelectorAll(".user-select-all");
for (var i = 0; i < elementsToSelectOnClick.length; i++) {
elementsToSelectOnClick[i].onclick = userSelectAll;
}
}
The final result should work for most browsers.
It is nice to know we can do a lot without having to rely on libraries :smiley: Some CSS and a bit of JavaScript goes a long way. It is also lovely to see that a simple solution can bring much value to your users, but you have to make sure they are communicated clearly!