Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addClass not working within setTimeout function

Tags:

jquery

demo

$('button').on('click',function(){
   setTimeout(function(){
      $(this).addClass('active');
   },500);
});

The active class should be added after 500 ms but it's not adding that is not changing it's background color.

like image 383
Navin Rauniyar Avatar asked Aug 30 '25 16:08

Navin Rauniyar


1 Answers

this doesn't refer to the clicked button inside the setTimeout() handler, you can use a simple closure variable to hold a reference to the clicked element and use it in the timeout handler

$('button').on('click', function () {
    var $el = $(this);
    setTimeout(function () {
        $el.addClass('active');
    }, 500);
});
like image 172
Arun P Johny Avatar answered Sep 02 '25 06:09

Arun P Johny