writingdeveloper
writingdeveloper

Reputation: 1076

jQuery click event and settimeout

You can access full code with github pages link below. Link

I'm developing the Matching game When I click each li selector, class of the li will be change so it can change card open. But I want to make it after 2 second, class of the li selector will change class.

$(document).ready(function () {
    $(".card").each(function () {
        $(this).click(function () {
            $(this).addClass("card open show"); // When click li element class will change to card open show
            setTimeout(function(){
                $(".card open show").addClass("card");
            }, 2000);
        });
    });
});

when I click the li selector class will change to card open show and I want to make it after 2 seconds class will change to card.

I don't know why it's not working.

Upvotes: 1

Views: 3131

Answers (3)

Luca Kiebel
Luca Kiebel

Reputation: 10096

You can use $().toggleClass() to toggle the classses before and after the timeout:

let element = this;
$(element).toggleClass("open show");
setTimeout(function() {
  $(element).toggleClass("open show");
}, 2000);

Upvotes: 0

Atul
Atul

Reputation: 430

Assuming every time click on any li it should close after 2 seconds.

$(this).click(function () {

var ele = $(this);
 $(this).addClass("open show"); 
            setTimeout(function(){
                ele.removeClass("open show");
            }, 2000);
        });

Upvotes: 0

brk
brk

Reputation: 50291

You need to remove the class from the element using $().removeClass()

Change $(".card open show").addClass("card"); to

 $(this).removeClass("open show");

Also there is no need to iterate over the elements. You can directly attach the click event to the element

$(document).ready(function () {
 $(".card").click(function () {
    // since element already have class card, no need to add same class again
    // only add the open and show class
    $(this).addClass("open show");
    setTimeout(function () {
      $(this).removeCLass(" open show");
    }, 2000);
  });

});

Upvotes: 1

Related Questions