How to create Expanding Cards using Javascript

We will see how we can create an expanding card that displays an expanded view of the card on click

Step 1) HTML:

Example code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0" />
    <title>Expanding Cards</title>
  </head>
  <body>
      
    <!-- Container -->
    <div class="container">
        
      <!-- Div with section and active -->
      <div class="section one active"></div>
        
      <!-- All another div with section -->
      <div class="section two"></div>
      <div class="section three"></div>
      <div class="section four"></div>
    </div>
  
  </body>
</html>

Step 2) CSS:

/* Setting container to flex and width to 80% of view port */
.container{
    display: flex;
    width: 80%;
}
/*Adding background image to each section*/
.one{
    background: url(img/one.jpg);
}
.two{
    background: url(img/two.jpg);
}
.three{
    background: url(img/three.jpg);
}
.four{
    background: url(img/four.jpg);
}
/* Background properties and transition effect to section  */
.section{
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    height: 80vh;
    cursor: pointer;
    flex: 0.2;
    margin:8px;
    position: relative;
    transition: all 0.7s ease-out;
} 
  
/* section with active class will grow flex to 3 times  */
.section.active{
    flex: 3;
}

Step 3) Javascript :

The querySelectorAll() method is used to return a collection of child elements with the class section.

The addEventListener() method is used to handle the click event for each card section.

Example code

// Selecting all sections with class of section
const sections = document.querySelectorAll('.section')
  
// On click event for each section 
sections.forEach((section)=>{
    section.addEventListener('click',()=>{
    // remove active class from all another section 
    // and add it to the selected section
        sections.forEach((section) => {
            section.classList.remove('active')
        })
        section.classList.add('active')
    })
})

Leave a comment

Your email address will not be published. Required fields are marked *