Follow @endyourif rss Facebook LinkedIn

Copy to clipboard with #JavaScript Copy to clipboard with #JavaScript

Published on Feb 3, 2020

This is such a little handy JavaScript function that allows you to create a button that will copy a block of content into the user's clipboard. The solution is to use the built-in execCommand function.



Using execCommand to copy text into clipboard



To start we need something that contains text. A very common scenario is a textarea with a block of HTML (e.g. when you're copying a Youtube embed video):







With our HTML created, I'm going to use an addEventListener on the click event. Inside the click event we can then use the execCommand function as follows:


document.querySelector('#copytoclipboard').addEventListener('click', function(event) {
	var copyTextarea = document.querySelector('#embedcode');
	copyTextarea.focus();
	copyTextarea.select();

	document.execCommand('copy');
});


The text inside the text area is now copied to the user's clipboard to paste at their leisure.

Tags: JavaScript | execCommand

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP