Here is an example of jQuery code that copies the current website URL to the clipboard when clicking a button with the class copy-current-url
:
Copy URL
Copy
<script>
$(document).ready(function () {
$('.copy-current-url').on('click', function () {
// Create a temporary input element
const tempInput = $('<input>');
$('body').append(tempInput);
// Set the current URL as the value
tempInput.val(window.location.href).select();
// Copy the text to the clipboard
document.execCommand('copy');
// Remove the temporary input element
tempInput.remove();
// Optionally, display a notification
alert('URL copied to clipboard!');
});
});
</script>
How it works:
- When the button is clicked, a temporary
<input>
element is created. - The current URL (
window.location.href
) is written into this element. - The text is copied to the clipboard using the
document.execCommand('copy')
command. - The temporary element is removed after copying.
- An optional notification is shown to indicate that the URL was successfully copied.
This approach works in most browsers. However, if you’re using modern methods, you can replace document.execCommand
with the navigator.clipboard
API for better browser support.