Add And Remove Active Class Onclick Javascript Codepen

4 min read Jun 22, 2024
Add And Remove Active Class Onclick Javascript Codepen

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

  1. Create a New Pen: Visit CodePen () and click "New Pen."
  2. HTML Structure: Let's start with a simple HTML structure. Add this to the HTML pane:
  • Item 1
  • Item 2
  • Item 3
  1. 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;
}
  1. 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

  1. querySelectorAll: This selects all the li elements within our ul and stores them in the listItems variable.
  2. forEach: We iterate over each li element in the listItems collection.
  3. addEventListener: We attach a click event listener to each li element.
  4. 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.

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.

Latest Posts