Set delay for the second click function jQuery

Viewed 367

I want the second click function to be delayed by 500ms, where do I insert this?

$(document).ready(function(){
  $('.dropToggler').click(function() {
    $(this).parent().addClass("open");
  });
    $('.acceptCta').click(function() {      //I want the delay on this function.
    $(this).parent().removeClass("open");
  });
});

Tried this too, didn't work:

$(document).ready(function() {
  $('.dropToggler').click(function() {
    $(this).parent().addClass("open");
  });
  setTimeout(function() {
    $('.acceptCta').click(function() {
      $(this).parent().removeClass("open");
    });
  }, 800);
});

2 Answers

You need to delegate and tell which element you are referring to when clicking and use that for setTimeout - removeClass function

var $this = $(this) // will be click function

setTimeout(function() {} does not know what is $(this) as we searching for the parents of the clicked event element.

$(document).ready(function() {
  $('.dropToggler').click(function() {
    $(this).parent().addClass("open");
  });
    $('.acceptCta').click(function() { 
     //This needed
      var $this = $(this)
      //delay removeClass
      setTimeout(function() {
        $this.parent().removeClass("open");
      }, 800);
    });
});

setTimeout(function(){ 
    //your code goes here
   alert("Hello"); 
}, 3000);//here you can set the time in milliseconds

you can use the setTimeout Function

Related