Pavan Yekabote
Pavan Yekabote

Reputation: 25

$(this) is not working in click event defined

$(document).ready(() => {
  $(".tabs-item").click(() => {
    $(".tabs-item").removeClass("active");
      $(this).addClass("active"); //This line is not at all working..
    });
  });

$(this) is not at all working. I have been trying with different methods. Like

$("tabs-item").click(() => {
  var x = $(this).attr("tab-data");
  console.log(x);
});

All I have got is Undefined for every attribute i have tried.

Upvotes: 0

Views: 56

Answers (2)

k32y
k32y

Reputation: 427

Why not do this instead?

$(document).ready(function(){

    $(".tabs-item").click(function(e){
       $(".tabs-item").removeClass("active");
       $(this).addClass("active");
    });

});

I don't see any special need for using the fat arrow => function notation.

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68685

Arrow function preserves the outer context - this refers to the context where the arrow function was defined. Replace arrow function with function declaration to let jQuery bind the appropriate context for the function.

$("tabs-item").click(function(){
    var x = $(this).attr("tab-data");
    console.log(x);
});

Or with arrow function you can get the event parameter in the parameters and access currentTarget property of it.

$("tabs-item").click((event) => {
    var x = $(event.currentTarget).attr("tab-data");
    console.log(x);
});

Function declaration approach is more preferable, because arrow functions are not provided for the event handlers. Just use function declaration and it's context will be bound to appropriate one.

Upvotes: 4

Related Questions