0

I can use this to get the id from my clicked button, but I cannot select the clicked button with this to run my setTimeout function.

$(".btn").click(function () {
      var userChosenColour = $(this).attr("id");
      $(this).addClass("pressed");
      setTimeout(function() {$(this).removeClass("pressed");} , 100);
    })

However, I can run it in this way by not using this:

$(".btn").click(function () {
  var userChosenColour = $(this).attr("id");
  $(this).addClass("pressed");
  setTimeout(function() {$("#" + userChosenColour).removeClass("pressed");} , 100);
})

Do I have any misconception on the keyword this?

Heretic Monkey
  • 10,498
  • 6
  • 45
  • 102

1 Answers1

0

The this keyword is quite different from other languages... I recommend this & object prototypes to know more.

For your problem, one simple and recommended solution would be:

$(".btn").click(function () {
  var $this = $(this) // Store the jQuery object and use it everywhere
  var userChosenColour = $this.attr("id");
  $this.addClass("pressed");
  setTimeout(function() {$this.removeClass("pressed");} , 100);
})
laruiss
  • 3,477
  • 1
  • 14
  • 27