How change icon on a button dynamically with JavaScript after 2 seconds when clicked?

92 views Asked by At

The main purpose of my script is to announce that the copy of the text has been successfully completed.

When I click on the button, the first icon change was ok, as is the toast display, and the text is correctly copied with the framework clipboard.js.

<button 
   class="btn btn-outline-success"
   id="url-rss" data-clipboard-text="Texte à copier">
      <i class="fa-regular fa-clipboard" id="icon"></i>
</button>

when i click on the button, 2 secondes after, I want the script change the button again to fa-circle-check to fa-clipboard.

I use clipboard.js, Bootstrap 5 (bundle) & Font Awesome.

This is my script :

document.addEventListener('DOMContentLoaded', function () {
    // Load of Clipboard.js
    let clipboard = new ClipboardJS('#url-rss')

    // Variable for the Toast with Bootstrap 5
    let toastCopie = new bootstrap.Toast(document.querySelector('#copieToast'), {
        animation: true,
        delay: 2500
    });

    // We listen #url-rss on click
    document.querySelector('#url-rss').addEventListener('click', async function() {
        // If Click on the <button> do a Toast()
        toastCopie.show()

        let iconElement = document.querySelector('#icon')

        // Change of the icon, first round
        iconElement.classList.remove('fa-clipboard')
        iconElement.classList.add('fa-circle-check')

        await new Promise(resolve => setTimeout(resolve, 2000));

        // Chnage of the icon, second round
        iconElement.classList.remove('fa-circle-check');
        iconElement.classList.add('fa-clipboard');
    })
});

I have copy an example of my script on codepen if anyone want try.

I have try with this too :

        setTimeout(function() {
            iconElement.classList.remove('fa-circle-check');
            iconElement.classList.add('fa-clipboard');
        }, 2000);

But after various attempts and research, my JavaScript skills aren't advanced enough for me to solve this problem on my own.

1

There are 1 answers

1
Matija On BEST ANSWER

Machou. you tried below code but maybe it didn't work correctly, right?

setTimeout(function() {
    iconElement.classList.remove('fa-circle-check');
    iconElement.classList.add('fa-clipboard');
}, 2000);

the main reason is that iconElement in above example is not correct, because it doesn't refer it's origin form after 2 seconds.

this will work fine if you correct your code like this.

setTimeout(function() {
   let iconElement = document.querySelector('#icon');   
   iconElement.classList.remove('fa-circle-check');
   iconElement.classList.add('fa-clipboard');
}, 2000);

iconElement must be redelcared in this scope. because if you change classname of svg element that change it's shape, past element does not exist anymore.

I tested this code in you codepen snippet. If you have any other javascript tacklings, please dm me. (It's my pleasure)