Search code examples
javascripthtmlcssclasschildren

How to close previous element when clicking a button on javascript


I am trying to display an image and its description by clicking a button. However, I want to close the previous box each time I click on another button. Can anyone please help me?

I've tried several method but couldn't figure it out.


Solution

  • I believe this is what you're trying to achieve. Each image is enclosed within a div element with a unique id and the CSS class image-container, the descriptions are hidden by default using CSS. Clicking a button toggles the id of that button to active and displays the corresponding photo and description.

    <!DOCTYPE html>
    <html>
    <head>
        <title>Image Description</title>
        <style>
            .image-container {
                display: none;
                text-align: center;
            }
    
            .image-container.active {
                display: block;
            }
    
            .description {
                display: none;
            }
    
            .description.active {
                display: block;
            }
        </style>
    </head>
    <body>
        <button onclick="toggleImageDescription('image1')">Show Image 1</button>
        <button onclick="toggleImageDescription('image2')">Show Image 2</button>
        <button onclick="toggleImageDescription('image3')">Show Image 3</button>
    
        <div id="image1" class="image-container">
            <img src="image1.jpg" alt="Image 1">
            <div class="description">Description for Image 1</div>
        </div>
        <div id="image2" class="image-container">
            <img src="image2.jpg" alt="Image 2">
            <div class="description">Description for Image 2</div>
        </div>
        <div id="image3" class="image-container">
            <img src="image3.jpg" alt="Image 3">
            <div class="description">Description for Image 3</div>
        </div>
    
        <script>
            function toggleImageDescription(imageId) {
                const imageContainer = document.getElementById(imageId);
                const description = imageContainer.querySelector(".description");
    
                // Close previously opened image containers
                const activeContainers = document.querySelectorAll(".image-container.active");
                activeContainers.forEach(container => {
                    container.classList.remove("active");
                });
    
                // Toggle visibility of the clicked image container and description
                imageContainer.classList.toggle("active");
                description.classList.toggle("active");
            }
        </script>
    </body>
    </html>