Rodrigo Dias
Rodrigo Dias

Reputation: 177

Function not show the parent classes after use setTimeOut - jQuery

After using setTimeout in a function that displays the classes of a parent element, the result in console.log is undefined.

How can I do this check of the classes after the user triggers a blur in the input?

jsfiddle

    <div class="field-wrapper field-pristine">
     <input type="text" class="field-item" value="test">
    </div>

    jQuery('body').on('blur', '.field-wrapper input.field-item', function() {
    setTimeout(function(){    
        console.log($( this ).closest('.field-wrapper').attr('class'));
    }, 1200);
    })

Upvotes: 0

Views: 234

Answers (4)

brk
brk

Reputation: 50291

You need to bind this with setTimeout

jQuery('body').on('blur', '.field-wrapper input.field-item', function() {
  setTimeout(function() {
    console.log($(this).closest('.field-wrapper').attr('class'));
  }.bind(this), 1200);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field-wrapper field-pristine">
  <input type="text" class="field-item" value="test">
</div>

Else use arrow function

jQuery('body').on('blur', '.field-wrapper input.field-item', function() {
  setTimeout(() => console.log($(this).closest('.field-wrapper').attr('class')), 1200);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field-wrapper field-pristine">
  <input type="text" class="field-item" value="test">
</div>

Upvotes: 1

Daniel Krom
Daniel Krom

Reputation: 10058

You are losing this pointer with the function, you can use arrow function that doesn't bind to this

jQuery('body').on('blur', '.field-wrapper input.field-item', function () {
    setTimeout(() => {
        console.log($(this).closest('.field-wrapper').attr('class'));
    }, 1200);
})

Upvotes: 2

amprew
amprew

Reputation: 261

This is because the context of this changes inside of the callback of the method setTimeout what you will have to do here is store $(this) like:

var myElement = $(this);

// then do the setTimeout and inside use `myElement` instead of `$(this)`
setTimeout(function(){    
  console.log(myElement.closest('.field-wrapper').attr('class'));
}, 1200);

Upvotes: 1

AntonyMN
AntonyMN

Reputation: 919

I know this is an easy fix but you need to define a new variable var that = this. This is because var this has changed in the new setTimeout function.

This is what I have done.

jQuery('body').on('blur', '.field-wrapper input.field-item', function() {
  var that = this;
  setTimeout(function() {
    console.log($(that).closest('.field-wrapper').attr('class'));
    alert($(that).closest('.field-wrapper').attr('class'));
  }, 1200);
 })

Upvotes: 1

Related Questions