Dima Vleskov Dima Vleskov - 5 months ago 19
jQuery Question

Using JavaScript, how to make elements appear one by one

How to make blocks appear one by one when I click a button? One click = one block appearing.

<div class="gallery">
<div class="block">
<div class="img"></div>
</div>
<div class="block">
<div class="img"></div>
</div>
<div class="block">
<div class="img"></div>
</div>
<div class="block">
<div class="img"></div>
</div>
</div>
<button id="btn"></button>

Answer

Below is a working example using jQuery (as mentioned in your tags). A couple things to note:

  1. I made a CSS class called hidden and added to each block.
  2. With jQuery, I created a click handler for he button that finds the first block with the hidden class and removes that class. This has the result of displaying that block.

Here is the complete code:

<!doctype html>
<html>
<head>
    <style>
        .hidden { display: none; }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
    <div class="gallery">
        <div class="block hidden">
            <div class="img"></div>
            first block
        </div>
        <div class="block hidden">
            <div class="img"></div>
            second block
        </div>
        <div class="block hidden">
            <div class="img"></div>
            third block
        </div>
        <div class="block hidden">
            <div class="img"></div>
            fourth block
        </div>
    </div>
    <button id="btn">Click me</button>

    <script>
        $(function () {
            $('#btn').click(function () {
                $('.gallery .hidden').first().removeClass('hidden');
            });
        });
    </script>
</body>
</html>
Comments