Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there an alternative to foreach in Js?

I have several identical divs and each of them contains a button that is hidden. I want to make button visible when you hover on the parent div. I wrote this code:

    const cardElements = document.querySelectorAll('.middle_section__president_section');
    const learnButtons = document.querySelectorAll('.president_section__button');

    cardElements.forEach((cardElement) => {
        cardElement.addEventListener('mouseover', () => {
            learnButtons.forEach((learnButton) => {
                learnButton.style.height = "50px";
                learnButton.style.opacity = "1";
                learnButton.style.border = "3px solid rgb(129, 129, 129)";
            });
        });
        
        cardElement.addEventListener('mouseout', () => {
            learnButtons.forEach((learnButton) => {
                learnButton.style.height = "0px";
                learnButton.style.opacity = "0";
                learnButton.style.border = "0px solid rgb(129, 129, 129)";
            });
        });    
    })

carElements is parent, learnButtons – child.

but with this code when i hover on one div buttons appears in every similiar div. How can i make button appear only on hovered div?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There’s no need to use JS for this. As Mister Jojo/traktor pointed out in their comments you can use the CSS :hover pseudo-class instead.

The key CSS line is .box:hover button { visibility: visible;} which means "when you hover over the parent container make its button visible".

.box { width: 50%; display: flex; flex-direction: column; border: 1px solid lightgray; margin: 0.25em; padding: 0.25em;}
button { visibility: hidden; margin: 0.25em 0; border-radius: 5px;  background-color: lightgreen; }
.box:hover button { visibility: visible;}
.box:hover, button:hover { cursor: pointer; }
<section class="box">
  Some text
  <button>Click for a surprise!</button>
</section>

<section class="box">
  Some text
  <button>Click for a surprise!</button>
</section>

<section class="box">
  Some text
  <button>Click for a surprise!</button>
</section>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading