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.".
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:
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>