Offscreen Text for Copy & Paste

By  on  

The relationship between HTML and CSS is special: mixing content via HTML with presentation from CSS to make an awesome presentation. Sometimes, however, you need to employ CSS tricks solely to enhance functionality. This could be one of those cases.

When browsing through the Firefox DevTools console code, I noticed a really clever technique for hiding text on screen but making sure it's present during a copy + paste. Here's the technique:

<p>Jenny don't change your number <span class="copy-only">8675309</span></p>
.copy-only {
  display: block;
  position: absolute;
  left: -9999999px;
  top: -9999999px;
}

With the CSS above, the screen displays "Jenny don't change your number" while copying that line would result in "Jenny don't change your number 8675309".

When you plant the text offscreen via CSS, it's still copied to the clipboard when the user does a copy operation. You're essentially picking and choosing what gets copied, which can be very valuable if you expect users to copy your content.

Recent Features

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

  • By
    Convert XML to JSON with JavaScript

    If you follow me on Twitter, you know that I've been working on a super top secret mobile application using Appcelerator Titanium.  The experience has been great:  using JavaScript to create easy to write, easy to test, native mobile apps has been fun.  My...

Incredible Demos

  • By
    HTML5 Input Types Alternative

    As you may know, HTML5 has introduced several new input types: number, date, color, range, etc. The question is: should you start using these controls or not? As much as I want to say "Yes", I think they are not yet ready for any real life...

  • By
    Elegant Overflow with CSS Ellipsis

    Overflow with text is always a big issue, especially in a programmatic environment. There's always only so much space but variable content to add into that space. I was recently working on a table for displaying user information and noticed that longer strings were...

Discussion

  1. Charlie

    Very nice, gotta love those little CSS tweaks.
    Small caveat, only works if the user double-clicks on line to select, won’t if it’s a “click-hold on first letter and drag cursor” kind of copy

  2. Does it work in all browsers? It’s very easy to use and simple, but I’m concerned that it could be too simple to work in every browser.

  3. These simple and small tweaks help a long way in designing. Thanks a lot for sharing :)

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!