Here I am giving 3 examples to copy URL to clipboard on button click using JavaScript, jQuery, and HTML.
Example -1: Copy URL to Clipboard on Button Click 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 Link to Clipboard on Button Click 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 URL to Clipboard Using HTML
<button onclick="prompt('Press Ctrl + C, then Enter to copy to clipboard',window.location.href)">Copy Link</button>
Leave a comment