You could just show the first one not visible. For a little improvement, instead of looking up the visibility for each function call, we cache the list of hidden blocks ($blocks
) at dom load.
At the end of the function the list of visible blocks is then updated (the one that was toggled on is displayed).
Note: this does not for dynamically added blocks that are added after the initial dom load, but the code could be easily updated for that.
$blocks = $('.block:not(:visible)');
function showBlock() {
var $block = $blocks.first().css('display', 'block');
$blocks = $blocks.not( $block );
}
.block {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="gallery">
<div class="block">
<div class="img"></div>
one
</div>
<div class="block">
<div class="img"></div>
two
</div>
<div class="block">
<div class="img"></div>
three
</div>
<div class="block">
<div class="img"></div>
four
</div>
</div>
<button id="btn" onclick="showBlock()">Show Block</button>