2

I am trying to add a class to a div in my html but would like to add a delay before doing so. I've got the following code below but it does not seem to be applying any sort of delay. Can anyone advise me of what I am doing wrong?

$("#globe").on('ended',function() {
  setTimeout(
    $('.faculty-info').addClass('cbp-spmenu-open'), 
    5000);
});
tmarwen
  • 15,750
  • 5
  • 43
  • 62
Javacadabra
  • 5,578
  • 15
  • 84
  • 152
  • possible duplicate of [jQuery: Can I call delay() between addClass() and such?](http://stackoverflow.com/questions/2510115/jquery-can-i-call-delay-between-addclass-and-such) – cmbuckley Sep 01 '14 at 08:48

3 Answers3

2

setTimeout requires a function definition as first parameter, so wrap whatever you want to do in an anonymous function like bellow

setTimeout(function(){
    $('.faculty-info').addClass('cbp-spmenu-open')
}, 5000);
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
0

You shoudl wrap your code (instructions to be performed in a delay fashion) in a function.

$("#globe").on('ended',function() {
  setTimeout( function() {
    $('.faculty-info').addClass('cbp-spmenu-open')
  }, 5000);
});

You may also need to declare a variable to hold the timeout value. This will give you the possibility to clear it once you are in need:

//Global timeout variable
var timeOut;

$("#globe").on('ended',function() {
  timeOut = setTimeout( function() {
    $('.faculty-info').addClass('cbp-spmenu-open')
  }, 5000);
});
tmarwen
  • 15,750
  • 5
  • 43
  • 62
0

You can use jQuery's .delay() and .queue() to handle this:

$("#globe").on('ended', function () {
    $('.faculty-info').delay(5000).queue(function () {
        $(this).addClass('cbp-spmenu-open').dequeue();
    });
});

Here's a JSFiddle. See also: jQuery: Can I call delay() between addClass() and such?

Community
  • 1
  • 1
cmbuckley
  • 40,217
  • 9
  • 77
  • 91