Skip to content

Instantly share code, notes, and snippets.

@genesisneo
Created February 24, 2021 08:08
Show Gist options
  • Save genesisneo/9d18d0e9857992d593652bc66dda320d to your computer and use it in GitHub Desktop.
Save genesisneo/9d18d0e9857992d593652bc66dda320d to your computer and use it in GitHub Desktop.
Copy current URL to clipboard with callback function.
/*
Examples:
copyCurrentUrl(() => {
Toastify({
text: "URL successfully copied.",
duration: 3000
}).showToast();
});
*/
function copyCurrentUrl (event, callback) {
// prevent default events
event.preventDefault();
// get current url
const currentUrl = window.location.href;
// create new input element
const input = document.createElement('input');
// set current url to input element value
input.setAttribute('value', currentUrl);
// append input to body
document.body.appendChild(input);
// select input value
input.select();
// trigger copy command
document.execCommand('copy');
// remove input from body
document.body.removeChild(input);
callback();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment