I have been trying to create a button that shows the text "copy to clipboard" initially, after clicking the text is copied to the clipboard and the button changes the innerHTMl text to "Copied!" and the button background changes to green. now, the button should reset to the text "copy to clipboard" and color also.
function copyText() {
navigator.clipboard.writeText("//text to be copied//");
var elem = document.getElementById("button").style.backgroundColor = 'green';
var elem = document.getElementById("button").innerHTML = "Copied!";
}
<div >
<button onclick="copyText()" id="button"><img src="images/clipboard.svg"> Copy to Clipboard</button>
</div>
CodePudding user response:
you can add a timeout inside your function on the bottom like this:
setTimeout(function() {
document.getElementById("button").style.backgroundColor = 'white';
document.getElementById("button").innerHTML = "Copy to Clipboard!";
}, 3000);
CodePudding user response:
In react or other frameworks/libraries will be easier, but for a while you can use an If statement.
function copyText()
{
navigator.clipboard.writeText
("//text to be copied//");
if(document.getElementById("button").text != 'Copied'){
var elem = document.getElementById("button").style.backgroundColor='green';
var elem = document.getElementById("button").innerHTML = "Copied!";
}
}
CodePudding user response:
There is a few things to do.
- set a timer
- reset background-color
- insert again the img and the text aside
You can do it this way:
function copyText() {
navigator.clipboard.writeText("//text to be copied//");
var elem = (document.getElementById("button").style.backgroundColor = "green");
var elem = (document.getElementById("button").innerHTML = "Copied!");
// give it a delay before the content of button is updated
setTimeout(() => {//timer
var button = document.getElementById("button");// fetch the button
button.textContent = "";//erase the text
button.style.backgroundColor = "revert";//reset background-color
button.insertAdjacentHTML(// insert you img and text
"beforeend",
'<img src="images/clipboard.svg"> Copy to Clipboard'
);
}, "1000");//duration in ms secondes before the function is fired 1000 is equal to 1second
}
<div >
<button onclick="copyText()" id="button"><img src="images/clipboard.svg"> Copy to Clipboard</button>
</div>
ressources
CodePudding user response:
You can create a delay async function with setTimeout
and clean your code like this:
const btn = document.getElementById('button');
const delay = (s) =>
new Promise((resolve) => setTimeout(resolve, s * 1000));
btn.addEventListener('click', async() => {
navigator.clipboard.writeText('//text to be copied//');
btn.className = 'copied';
btn.innerText = 'Copied';
await delay(2);
btn.classList.remove('copied');
btn.innerText = 'Copy to Clipboard';
});
.copied {
background-color: green;
color: white;
}
<div >
<button id="button">Copy to Clipboard</button>
</div>