Mido
Mido

Reputation: 351

Remove THIS element after change it's class

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

Upvotes: 0

Views: 63

Answers (2)

Naga Sai A
Naga Sai A

Reputation: 10975

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>

Upvotes: 3

Benedikt
Benedikt

Reputation: 607

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

Upvotes: 1

Related Questions