Copy URL to Clipboard on Button Click Examples

Here are 3 examples showing how to copy a URL to the clipboard on a button click using JavaScript, jQuery, and HTML.

Example -1: Copy Page URL using JavaScript

In the below code, the JavaScript function copyToClipboard is written and specified on the onclick event of the button.

<!DOCTYPE html>
<html>

<body>

<button onclick="copyToClipboard()">Copy Link</button>

<script>
function copyToClipboard(text) {
var inputc = document.body.appendChild(document.createElement("input"));
inputc.value = window.location.href;
inputc.focus();
inputc.select();
document.execCommand('copy');
inputc.parentNode.removeChild(inputc);
alert("URL Copied.");
}
</script>

</body>

</html>

Output:

The output would be a button, and on the click, you will get the message "URL Copied.".

Copy page URL JavaScript

Example -2: Copy the Link to Clipboard Using jQuery

The following is an example of a Copy URL to the clipboard using jQuery.

<!DOCTYPE html>
<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var $temp = $("<input>");
var $url = $(location).attr('href');
$('#btn').click(function() {
$("body").append($temp);
$temp.val($url).select();
document.execCommand("copy");
$temp.remove();
$("p").text("URL copied!");
});
});
</script>
</head>

<body>
<p></p>
<input id="btn" type="button" value="Copy Link" />
</body>

</html>

Output:

Copy current URL example

Example -3: Copy Current URL to Clipboard Using HTML

This example shows a simple way to add a copy link button using HTML.

<button onclick="prompt('Press Ctrl + C, then Enter to copy to clipboard',window.location.href)">Copy Link</button>

Output:

Copy page location example
Vinish Kapoor
Vinish Kapoor

Vinish Kapoor is a seasoned software development professional and a fervent enthusiast of artificial intelligence (AI). His impressive career spans over 20 years, marked by a relentless pursuit of innovation and excellence in the field of information technology. As an Oracle ACE, Vinish has distinguished himself as a leading expert in Oracle technologies, a title awarded to individuals who have demonstrated their deep commitment, leadership, and expertise in the Oracle community.