Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery delay not working

Tags:

jquery

$('.transparent').removeClass('transparent').delay(2000).addClass('not_transparent').delay(4000) 

I have a div that is semi transparent and then want to switch it to not transparent. But the jQuery .delay(); method doesn't seem to work here. I've tried .fadeIn(); instead and that works with a delay but it doesn't work the changing classes.

like image 233
thenengah Avatar asked Dec 28 '10 06:12

thenengah


People also ask

How to use delay in jQuery?

The jQUery delay () method sets a timer to delay the execution of the next item in the queue. Syntax: $(selector). delay (speed, queueName)

How to delay animation in jQuery?

jQuery delay() Method The delay() method sets a timer to delay the execution of the next item in the queue.

What is delay () in JavaScript?

Conclusion. setTimeout() is a method that will execute a piece of code after the timer has finished running. let timeoutID = setTimeout(function, delay in milliseconds, argument1, argument2,...); The delay is set in milliseconds and 1,000 milliseconds equals 1 second.

How do you make a delay in JavaScript?

The standard way of creating a delay in JavaScript is to use its setTimeout method. For example: console. log("Hello"); setTimeout(() => { console.


2 Answers

.delay() is used for items that are part of a queue, like animations. A simple addClass is not queued.

You could use setTimeout.

var trans = $('.transparent').removeClass('transparent'); setTimeout(function() {     trans.addClass('not_transparent'); }, 2000); 

As an alternative, you could add the non-queued item to the queue using .queue(), though I think a setTimeout would be better.

$('.transparent').removeClass('transparent').delay(2000).queue(function(nxt) {       $(this).addClass('not_transparent');       nxt(); }); 
like image 133
user113716 Avatar answered Oct 03 '22 19:10

user113716


I know this is an old question, but there's still a lot of traffic coming here from google so I'll add my two cents;

You could use something like -

$('.transparent').fadeIn().delay(500).queue(function(){    $('.transparent').addClass('yourclass');  });

You can pass a function to the queue in order to execute them after the delay. Have been using this myself for very similar examples.

like image 37
Lewis Avatar answered Oct 03 '22 17:10

Lewis