How to create Expanding Cards using HTML, CSS and Javascript ?
Last Updated :
29 Jul, 2024
Improve
Creating expanding cards using HTML, CSS, and JavaScript involves creating a set of cards that expand when clicked.
Approach
- Selection of Sections:
- The code starts by selecting all HTML elements with the class ‘section’ using the
document.querySelectorAll('.section')
method. - This creates a NodeList containing all elements with the specified class.
- The code starts by selecting all HTML elements with the class ‘section’ using the
- Event Listener for Each Section:
- A
forEach
loop is used to iterate over each section in the NodeList (sections
). - For each section, an event listener for the ‘click’ event is added.
- A
- Removing ‘active’ Class from Other Sections:
- Inside the click event handler, another
forEach
loop is used to iterate over all sections (sections
). - For each section in this loop, the ‘active’ class is removed using
section.classList.remove('active')
.
- Inside the click event handler, another
- Adding ‘active’ Class to Clicked Section:
- After removing the ‘active’ class from all sections, the ‘active’ class is added to the currently clicked section using
section.classList.add('active')
.
- After removing the ‘active’ class from all sections, the ‘active’ class is added to the currently clicked section using
Example: We are following the above-explained approach.
<!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>
/* 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;
}
// 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')
})
})
Output: Click here to see live code output