Copy to Clipboard!

JavaScript Sep 10, 2015

Today, I will share some ideas about making 'Copy to Clipboard!' button using JavaScript. This is very common feature that many site already has for good user experience.

There are libraries that can be used for it like ZeroClipboard through which we can accomplish this and do much more things. For simple 'Copy to Clipboard' button, we can also use the following code. It is simple & easy. It adds a temporary input box into page for selection, copies the required text and then selects it for clipboard. At the end we delete this temporary input box.

$('.clipboard').click(function(){
		var $temp = $("<textarea>");
		$("body").append($temp);
		$temp.val($(this).parent().parent().text()).select();
		document.execCommand("copy");
		$temp.remove();
		$(this).parent().find('.copied').show(1).css('display','inline-block').fadeOut(3000);
	});

Click on clipboard icon on code block above to see it in action.

Happy Coding!

Related Tags:

JavaScript