Lars Breuren
Lars Breuren

Reputation: 31

Change button on click for few seconds

I would like to change a button's image source for a few seconds on click.

For now i have this:

setTimeout(function(){document.getElementById('buttonImg').src='images/button2.png';},5000);

But what this does is changing the image after 5 seconds instead of for 5 seconds. I can't figure out how to change the setTimeout function to do so

Upvotes: 2

Views: 964

Answers (3)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You need to keep track of the original image so that you can replace with that after 5000 milliseconds. Something like this,

function clickBtn(){
 var originalSrc = document.getElementById('buttonImg').src;
 document.getElementById('buttonImg').src = 'https://www.freeiconspng.com/minicovers/submit-button-png-18.png'
  setTimeout(function(){
    document.getElementById('buttonImg').src=originalSrc;
  },5000);
}
<img id='buttonImg' src='https://www.freeiconspng.com/minicovers/submit-button-png-9.png' onclick='clickBtn()' />

Upvotes: 0

Jo&#227;o Cunha
Jo&#227;o Cunha

Reputation: 15

You can do this!

document.getElementById('buttonImg').src='images/button2.png';
 setTimeout(function() {
     document.getElementById('buttonImg').src='[the source of the original image]';
 } ,5000);

Upvotes: 0

Ludovic Feltz
Ludovic Feltz

Reputation: 11916

The function setTimeout execute the first parameters after a delay given in the second parameter. So first change your image imediatly:

document.getElementById('buttonImg').src='images/button2.png';

Then just reset to previous image after a delay of 5s (5000ms):

setTimeout(function(){
     document.getElementById('buttonImg').src='images/button1.png';
},5000);

Upvotes: 3

Related Questions