2

I have created several div-elements under class name "image-part" and am trying to animate them using this script:

$(document).ready(function() {
  $('.image-part').each(function() {
    var id = setInterval(frame, 3000);

    function frame() {
      if ($(this).css("visibility") === "hidden") {
        $(this).css("visibility", "visible");
      } else {
        $(this).css("visibility", "hidden");
      }
    }
  });
});
.image-part {
  width: 33.33%;
  height: 60px;
  background-color: black;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="image-part" style="visibility:hidden"></div>
<div class="image-part"></div>
<div class="image-part"></div>
<div class="image-part"></div>

Nothing is happening, is there anyone that can help? Thanks!

0

1 Answer 1

4

The issue is because the scope of this within the setInterval() handler will not be a reference to any of the .image-part elements.

To fix this you can re-arrange the logic so that you execute the each() loop within the interval, like this:

$(document).ready(function() {
  setInterval(function() {
    $('.image-part').css('visibility', function(i, v) {
      return v == 'visible' ? 'hidden' : 'visible';
    });
  }, 3000);
});
.image-part {
  width: 33.33%;
  height: 60px;
  background-color: black;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="image-part" style="visibility:hidden"></div>
<div class="image-part"></div>
<div class="image-part"></div>
<div class="image-part"></div>

Note that I changed the logic to be more succinct by using a single call to css() with a function provided. The outcome is identical to your original intention, though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.