Adding an Active Class with OnClick in JavaScript (CodePen Example)
This article will guide you through the process of adding an "active" class to an element using JavaScript's onclick
event in CodePen. This technique is commonly used for creating navigation menus, tabbed interfaces, or dynamic interactions in web pages.
Understanding the Concept
The core idea is to use the onclick
event to trigger a JavaScript function that modifies the class attribute of the target element. We'll add the "active" class to the clicked element while removing it from any previously active elements.
CodePen Example
Active Class on Click
Explanation:
-
HTML Structure: We create a simple unordered list (
<ul>
) with list items (<li>
). Each list item represents a navigation link and has the classnav-item
. We use theonclick
attribute to call thesetActive
function when an item is clicked, passing the clicked element (this
) as an argument. -
CSS Styles: Basic styles are applied to the navigation items, and the
.active
class is used to apply a background color to the selected item. -
JavaScript Function:
setActive(element)
: This function takes the clicked element (element
) as input.- Remove Existing Active Class: It uses
querySelectorAll
to select all elements with the classnav-item
and then iterates through them usingforEach
. For each element, it removes theactive
class usingclassList.remove('active')
. - Add Active Class: It adds the
active
class to the clicked element usingelement.classList.add('active')
.
Key Points
- Event Listener: The
onclick
attribute is a simple way to trigger a function on click. You can also use theaddEventListener
method for more advanced event handling. - Class Manipulation:
classList.add()
andclassList.remove()
are useful methods for dynamically managing CSS classes. - Specificity: The CSS styles for
.active
must be specific enough to override the default styles of the.nav-item
class.
By applying these techniques, you can easily create dynamic navigation menus, tabbed interfaces, and other interactive elements on your web pages.