Grillo
Grillo

Reputation: 5

Jquery - TimeOut Function

I'm trying to run the following jQuery Code.

$('body.player').find('.tab').click(function(){
      $('.playerLoaders').addClass('loading');

      setTimeout(function() {
            if( !$(this).hasClass('active') ){
                 $('.playerLoaders').removeClass('loading');
                 $('.tab-content[data-tab="' + $(this).attr('data-tab') + '"]').addClass('active').siblings().removeClass('active');
                 $(this).addClass('active').siblings().removeClass('active');
            }
            return false;
      },5000);
});

But something is not working quite right.
The div-tag "playerLoaders" is working perfectly, but the tab-content-div is not removing the active class, and adding it to the active tab.

If I delete the TimeOut-function, the tabs are working just fine.

What am I doing wrong?

Upvotes: 0

Views: 81

Answers (1)

carlosdubusm
carlosdubusm

Reputation: 1083

Inside the setTimeout function, 'this' is referencing the setTimeout context, and not the outer function context. You should get a reference to the outer function context. Consider this:

$('body.player').find('.tab').click(function(){
      var self = this;
      $('.playerLoaders').addClass('loading');

      setTimeout(function() {
            if( !$(self).hasClass('active') ){
                 $('.playerLoaders').removeClass('loading');
                 $('.tab-content[data-tab="' + $(self).attr('data-tab') + '"]').addClass('active').siblings().removeClass('active');
                 $(self).addClass('active').siblings().removeClass('active');
            }
            return false;
      },5000);
});

If you want to keep using 'this' inside the setTimeout function, you can also bind it like this:

setTimeout((function() {
            if( !$(this).hasClass('active') ){
                 $('.playerLoaders').removeClass('loading');
                 $('.tab-content[data-tab="' + $(this).attr('data-tab') + '"]').addClass('active').siblings().removeClass('active');
                 $(this).addClass('active').siblings().removeClass('active');
            }
            return false;
}).bind(this),5000);

Upvotes: 1

Related Questions