1

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.

3 Answers 3

1

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);
  });

});
Sign up to request clarification or add additional context in comments.

Comments

0

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);
        });

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.