JQuery Copy to Clipboard Example

How to copy span, div, or other HTML element contents to clipboard using JQuery

JQuery Copy Span or Div Contents to Clipboard ExampleIn this blog, I provide examples of code I have written or used over the years. With each post, I provide the ability for you the user to copy the code contents to the clipboard so you can paste it into your page. This handy copy to clipboard logic enables you to copy the contents of the code block without having to select it first. Just click the copy hyperlink and the script does the rest.

I particularly like the example below because I can use it in my blog post without having to embed script in the post itself. I simply load a script function in the head tag of my pages and provide a structured link in the post body that identifies the span (or pre tag in my blog) that I want to copy. The script selects the range of data in the span, highlights it, copies it to the clipboard, then alerts the user the copy has completed.

The script monitors for a click event on all elements on the page with a name=”copy_pre”. All of our copy links are named “copy_pre”. Each link has a unique ID that matches the ID of the span we want to copy.

The copy script:
Continue reading “JQuery Copy to Clipboard Example”