Dreams
Dreams

Reputation: 8506

How to add time when use toggleClass?

Below is my code..

$(document).ready(function(){
  $("#toggle-btn").click(function(){
    $(".example").toggleClass("with-text");
  });
});

How to add time to when toggleClass? For example, any where I can add "5000" so it will add class in 5 seconds?

Thanks.

Upvotes: 0

Views: 479

Answers (3)

Nageshwar Reddy Pandem
Nageshwar Reddy Pandem

Reputation: 1047

just do like this. This creates a animation. So if you want the new text to fade in take this.

  $("#toggle-btn").click(function(){
    $(".example").toggleClass("red",5000);
  });

DEMO

Upvotes: 1

kovogel
kovogel

Reputation: 1030

you can use setTimeout. Try the following code:

$(document).ready(function(){
  $("#toggle-btn").click(function(){
    $("#toggle-btn").prop('disabled', true);
    setTimeout(function(){
      $(".example").toggleClass("with-text");
      $("#toggle-btn").prop('disabled', false);
     },5000);
    });
});

Edit: added disabled attribute so you can only click it if the timeout is over.

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

Use setTimeout

var timer = null;
$("#toggle-btn").click(function(){
  if(timer != null){
   clearTimeout(timer )
  }
  timer = setTimeout(function () { $(".example").toggleClass("with-text"); }, 5000);
});

Upvotes: 1

Related Questions