How do i copy the current page url to the clipboard in JavaScript?
To create a functional "Copy to Clipboard" button that copies the current URL when clicked, you can use a combination of HTML and JavaScript. Here is a complete example:
HTML
<button onclick="copy()"> Copy </button> <input id="copy-link"></input> <div id="copy-message" role="status">Link copied!</div>
- <button onclick="copy()"> Copy </button>: This button element calls the copy() function when it is clicked.
- <input id="copy-link"></input>: This input field will temporarily hold the URL to be copied.
- <div id="copy-message" role="status">Link copied!</div>: This div element will display a message confirming that the link has been copied. The role="status" attribute is used for accessibility purposes, announcing the status message to screen readers.
If you want to hide the input tag, you can set a small height and width, like 5px, and remove the border. Do not use display: none or visibility: hidden CSS on the input field, as the copy feature does not work for hidden elements.
JS
function copy() { var url = document.getElementById("copy-link"); var msg = document.getElementById("copy-message"); // Set the input field's value to the current page's URL url.value = window.location.href; // Focus on the input field and select its contents url.focus(); url.select(); // Display the confirmation message msg.style.display = "inline"; // Copy the selected text to the clipboard document.execCommand("copy"); // Hide the confirmation message after 2 seconds setTimeout(function() { msg.style.display = "none"; }, 2000); };
This functionality is useful for web pages where users might need to quickly copy the page URL to share it with others.