0

I'm trying to delete element 'this' ,500ms after changing its class, but it does not work

     $('.card').click(function() {
            setTimeout(function(){
                $(this).remove();
                console.log('removed');
            },500);
            $(this).toggleClass("card card-used");
     });

and HTML

<div class="card">asdasd</div>

I can see "removed" in my console log but it wasn't remove()

PayamB.
  • 706
  • 1
  • 9
  • 28
Mido
  • 341
  • 2
  • 15

2 Answers2

3

To achieve expected result, use arrow function to inherit this from the parent scope i.e .card , as this inside setTimeout function refers to window object

Please refer this link for more details- Lexical Scope in JavaScript

$('.card').click(function() {
            setTimeout(() => {
                $(this).remove();
                console.log('removed');
            },500);
            $(this).toggleClass("card card-used");
     });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">asdasd</div>
Naga Sai A
  • 10,771
  • 1
  • 21
  • 40
1

As already described, this belongs to the click context and cannot be accessed in the callback. But you can store it into a variable and access it in the callback.

$('.card').click(function() {
        var self = this;
        setTimeout(function(){
            $(self).remove();
            console.log('removed');
        },500);
        $(this).toggleClass("card card-used");
 });
Benedikt
  • 517
  • 4
  • 18