Adding and Removing Active Class on Click with JavaScript (CodePen Example)
This article will demonstrate how to add and remove an "active" class to an HTML element using JavaScript when it's clicked, while also highlighting the use of CodePen for testing and sharing your code.
Understanding the Basics
The core idea revolves around using JavaScript to manipulate the classList
property of an HTML element. We'll use the add()
and remove()
methods to dynamically manage the "active" class.
CodePen Setup
- Create a New Pen: Visit CodePen () and click "New Pen."
- HTML Structure: Let's start with a simple HTML structure. Add this to the HTML pane:
- Item 1
- Item 2
- Item 3
- CSS Styling: In the CSS pane, add some basic styles to make our list items visually appealing:
ul {
list-style: none;
padding: 0;
}
li {
padding: 10px;
border-bottom: 1px solid #ddd;
}
li.active {
background-color: #eee;
}
- JavaScript Logic: Now, for the core functionality, add this JavaScript code to the JavaScript pane:
const listItems = document.querySelectorAll('li');
listItems.forEach(item => {
item.addEventListener('click', () => {
// Remove 'active' from all list items
listItems.forEach(listItem => {
listItem.classList.remove('active');
});
// Add 'active' to the clicked item
item.classList.add('active');
});
});
Explanation
querySelectorAll
: This selects all theli
elements within ourul
and stores them in thelistItems
variable.forEach
: We iterate over eachli
element in thelistItems
collection.addEventListener
: We attach a click event listener to eachli
element.- Click Handler: When a list item is clicked, the click handler executes.
- It first removes the
active
class from all list items. - Then, it adds the
active
class to the clicked list item.
- It first removes the
Running and Testing
You can now run your CodePen and click on different list items. Observe how the active
class is dynamically toggled.
CodePen Benefits
- Live Preview: You can see your code changes reflected in real-time.
- Sharing: CodePen provides easy ways to share and embed your code snippets.
- Collaboration: You can collaborate with others on code projects.
Conclusion
This simple example demonstrates the power of JavaScript for dynamically styling your web pages. CodePen provides an excellent platform for learning, experimenting, and sharing your JavaScript code. You can build upon this foundation to create more complex interactive elements.