Dima Vleskov Dima Vleskov - 19 days ago 5
Javascript Question

how to hide all blocks with javasctipt

I have 5 blocks, one by one they appear(4 blocks), except last (block #5), and I don't understand why the last don't want. When all blocks are shown the hide and everything starts again. I would appreciate if you explain me why it happen.



$(function() {
$('div').addClass('hidden');
var i = setInterval(showBlock, 1000);

function showBlock() {
var x = $("div.hidden:first").removeClass("hidden");
if ($("div.hidden").length === 0) {
$('div').addClass('hidden');
}
}
});

.hidden {
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>




Answer

I'm not sure if I understand you well. I understand that it works well untill 4th block is spawned, then 5th block doesn't spawn but all desapear? If so, then the problem is in your "code" order.

1st you remove class "hidden" class from "div"

 var x = $("div.hidden:first").removeClass("hidden");

then in the same iteration you check if there are any "hidden divs" if not then you make all of "div" hidden.

if ($("div.hidden").length === 0) {
      $('div').addClass('hidden');
    }

I think it should work correctly if you change the order and add return to "if"

if ($("div.hidden").length === 0) {
  $('div').addClass('hidden');
  return
}
var x = $("div.hidden:first").removeClass("hidden");
Comments