natural design and informed content

Squarespace: Click to Select Text and Copy to Clipboard

If you've ever wondered how you can let the a visitor easily copy to their clipboard from your site, the best way is to just highlight text for them.

When they click on certain content, in this case a code block, we can select the text. Then they can copy it by:

  • with the mouse: right-click > Copy
  • on the keyboard: or ctrl + c
Example: On Quora where when you click the share URL, it gets highlighted.

Example: On Quora where when you click the share URL, it gets highlighted.

jQuery

First add jQuery. Then, in Settings → Code Injection → Header:

  // Add this inside $(document).ready(function(){

  // Code click highlight
  $('pre.source-code').click(function(){
    var range, selection;
    if (window.getSelection) {
      selection = window.getSelection();
      range = document.createRange();
      range.selectNodeContents(this);
      selection.removeAllRanges();
      selection.addRange(range);
    } else if (document.body.createTextRange) {
      range = document.body.createTextRange();
      range.moveToElementText(this);
      range.select();
    }
  });

Now when a visitor clicks into a code block, the text will get highlighted and they can easily copy and paste it elsewhere. In fact, you probably already saw this in action by clicking the code right above this. ☺

squarespace-select-highlight-click-code

Let me know in the comments if you're using this on your Squarespace blog and if you've found any other blocks to use it on besides code.