Albert Nemec Albert Nemec - 6 months ago 11
jQuery Question

Function doesn't work - (this) changes it's value within it

I have this simple code that

toggle
s all elements of a class
thumbnail
except of the one clicked. Then after 2seconds a specific class should be added or removed to clicked element, depending on whether it's already selected.

The problem is with
setTimeout
(most likely) as it won't run my function, that checks via
if else
if clicked element should be selected or unselected, and then adds/remove
selected-ser
class.

$(document).ready(function(){
$(".thumbnail").click(function(){
$('.thumbnail').not(this).toggle(2000);

setTimeout(function() {
if ($(this).hasClass('selected-ser')) {
$(this).removeClass('selected-ser');
} else {
$(this).addClass('selected-ser');
}
}, 2000);
});
});


I really tried to search for similar topics already solved, but I don't understand the way it doesn't work (It may be the function itself that's wrong, but I have no clue)

Thank you very much.

Edit: as it seems this topic adresses the same issue. I wasn't able to search for it before, as I didn't know the problem was with "owner of
this
". Thus I'm renaming this topic to "Function doesn't work - (this) changes it's value within it." So people dealing with same problem canbit more eaisly search for it, not knowing why doesn't the function work properly.

Thank you

Answer

If you use a variable to reference $(this) then call it in inside of setTimeout it will do what you want. I added some css so you can see what's happening, but the example below will do what you want:

$(document).ready(function() {
  var $this = $(this);
  $(".thumbnail").click(function() {
    var $this = $(this);

    function changeClass() {
      $this.toggleClass('selected-ser');
    }
    $('.thumbnail').not(this).toggle(2000);

    setTimeout(function() {
      changeClass();
    }, 2000);
  });
});
.thumbnail {
  border: solid;
}
.selected-ser {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="thumbnail">
  <p>
    Content
  </p>
</div>
<div class="thumbnail">
  <p>
    Content
  </p>
</div>
<div class="thumbnail">
  <p>
    Content
  </p>
</div>
<div class="thumbnail">
  <p>
    Content
  </p>
</div>