Costa Michailidis
Costa Michailidis

Reputation: 8178

jQuery conditional addClass not working

Having a little hang up with jQuery addClass. I have a #story div in my markup that shrinks down when it acquires the "away" class, and then pops back up when it looses that class.

Here's the snag:

$('#story div.x').on('click', function () {
  if (!$('#story').hasClass('away')) {
    $('#story').addClass('away');
  }
});

The code above simply adds a blank class="" to my story element, but...

$('#story div.x').on('click', function () {
  if (!$('#story').hasClass('away')) {
    setTimeout(function () {
      $('#story').addClass('away');
    }, 1000);
  }
});

That code adds the appropriate class="away" attribute.

What gives?

Upvotes: 0

Views: 270

Answers (1)

ieeehh
ieeehh

Reputation: 674

It sounds like there is another event updating the class, or perhaps the element is not yet ready but becomes available after 1 second, perhaps after an ajax call or when the DOM is ready.

Could that be it?

Upvotes: 1

Related Questions