I'm developing a script to simplify the reformatting of copied text, specifically phone numbers. I aim to paste the text into a textbox and have the formatted output automatically copied to my clipboard to reduce manual efforts.
The function for updating the clipboard only triggers with a genuine click event. I've tried multiple methods like programmatically invoking .click(), dispatching a "click" event, using async/await, and promises
JSFiddle Code: https://jsfiddle.net/ByteBender/7bukf5xh/9/
document.getElementById('myInput').addEventListener('paste', event => {
const contents = event.clipboardData.getData('text')
if (contents.length >= 9) {
event.preventDefault()
const formattedNumber = formatPhoneNumber(contents)
myInput.value = formattedNumber
copyToClipboard()
// Also failed to copy
//myButton.click()
// Also failed to copy
//setTimeout( () => myButton.dispatchEvent(new Event('click')), 500 )
}
});
function copyToClipboard() {
var copyText = document.getElementById("myInput");
copyText.select();
copyText.setSelectionRange(0, 99999); // For mobile devices
navigator.clipboard.writeText(copyText.value)
.then(()=> console.log('success!'))
.catch(err=>console.error(`fail: ${err}`))
}
// Also failed to copy
/* function tempButton(){
var button = document.createElement('button');
button.innerHTML = 'click me';
button.onclick = function(){
copyToClipboard();
return false;
};
document.body.appendChild(button);
//button.click()
} */