I have a div where when I click it, it adds a class of 'playing'. Then, after 10 seconds, I want to add a class of 'finished'.
I have this code, but how do I time it so after 10 seconds, it adds the class of finsihed?
$('.albums img').on('click',function(){
$(this).addClass('playing');
});
Any help is appreciated!
Thanks a ton everyone. I used this question to show ~30 students at HackerYou how to use stackoverflow to get top notch help from the munity.
I have a div where when I click it, it adds a class of 'playing'. Then, after 10 seconds, I want to add a class of 'finished'.
I have this code, but how do I time it so after 10 seconds, it adds the class of finsihed?
$('.albums img').on('click',function(){
$(this).addClass('playing');
});
Any help is appreciated!
Thanks a ton everyone. I used this question to show ~30 students at HackerYou how to use stackoverflow to get top notch help from the munity.
Share Improve this question edited Nov 22, 2013 at 15:49 wesbos asked Nov 22, 2013 at 1:54 wesboswesbos 26.3k31 gold badges108 silver badges144 bronze badges 2- 1 Check out .delay() function. – Yuriy Galanter Commented Nov 22, 2013 at 1:56
- 1 while you are at it @Wes - remind them to do a bit of research into their problem and ask specific questions (too broad, or not-researched questions tend to get down-voted). Also worth noting that, when possible, posting your code to a service like JSFiddle, JSBin or similar tends to speed up the responses – blurfus Commented Nov 22, 2013 at 17:25
3 Answers
Reset to default 14Try using setTimeout specifying 10 seconds delay.
$('.albums img').on('click',function(){
var $this = $(this).addClass('playing');
window.setTimeout(function(){
$this.addClass('finsihed');
}, 10000); //<-- Delay in milliseconds
});
You can use .delay() along with .queue()
$('.albums img').on('click', function () {
$(this).addClass('playing').delay(3000).queue(function () {
$(this).addClass('finsihed')
});
});
Demo: Fiddle
You can use the function setTimeout()
to invoke a callback function after 10 seconds.
For example.
var timeout = null;
$('.albums img').on('click', function() {
var self = this;
$(self).addClass('playing');
// clear previous timeout if it exists
timeout && clearTimeout(timeout);
// set the timeout
timeout = setTimeout(function() {
$(self).addClass('finished');
// 10 seconds
}, 10e3);
});