Bileberda
Bileberda

Reputation: 17

This selector doesn't work inside time out

Got a hidden div that has to show after a couple of seconds delay, and get a style based on its height. These hidden divs are dynamic. So, each of them has a unique height. Can't find hidden div's height, so, I've added the height calculation after class that hides the element is removed. Now, when I use actual class or remove timeout, script seems to be working. When using (this) inside timeout- nothing happens, and there are no errors in console.

if ($(".bubble")[0]) {
  $(".bubble").each(function() {
    setTimeout(function() {
      $(this).removeClass("hide");
      var bubblehe = $(this).height();
      $(this).css('top', bubblehe);
    }, 2000)

  });

  $(document.body).click(function() {
      $(".bubble").addClass("hide");
    }
  }
.hide (display:none;)

Upvotes: 0

Views: 143

Answers (2)

Taplar
Taplar

Reputation: 24965

//cache your repeated selector
var $bubble = $('.bubble');

//length > 0 is truthy
if ($bubble.length) {
  $bubble.each(function() {
    //cache your jQuery instantiation
    //this solves the changing value of this in the timeout
    //and stops duplicate jQuery instantiation
    var $this = $(this);
    
    setTimeout(function() {
      $this
        .removeClass("hide")
        .css('top', $this.height());
    }, 2000);
  });

  $(document.body).click(function() {
      $bubble.addClass("hide");
  });
}
html,body { min-width: 640px; min-height: 480px; }
.hide { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bubble hide">Bubble 1</div>
<div class="bubble hide">Bubble 2</div>

Upvotes: 0

Andrii Starusiev
Andrii Starusiev

Reputation: 7774

setTimeout has it's own context so this in it will not be your node

if($(".bubble")[0]) {       
        $(".bubble").each(function(){
            const self = this;
            setTimeout(function(){
                $(self).removeClass("hide");
                var bubblehe = $(this).height();
                $(self).css('top',bubblehe);
            }, 2000)

        });

        $(document.body).click(function(){
            $(".bubble").addClass("hide");
        }
}

Upvotes: 2

Related Questions