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
Get more Vinish.dev tutorials on Google

See my articles more often when you search Google.

Vinish Kapoor
Vinish Kapoor

An Oracle ACE, author of four books on Oracle APEX, SQL and PL/SQL, and Oracle Forms, and a software developer building Oracle database applications since 2001.

guest

0 Comments
Oldest
Newest Most Voted