How to pass an element to a JavaScript onclick function and assign a class to that clicked element
You can use this
inside the onclick
event to target the clicked HTML element, then apply element.classList.add('class-name')
to assign a new class:
In this scenario, clicking the button calls the highlight
function, passing in this
(the button element), which is then used to add the 'active' class to the button.
Interacting with multiple elements
When you're dealing with multiple clickable items like tabs or menu items, you'd typically only want the item you clicked on to be active. Let's take a look at how to achieve that:
The script first turns off active status of every other tab, then fires up the clicked tab. Lightbulb moment, huh?!
Seriously leveled up event handling
From inline to external with addEventListener
To improve code organization and maintainability, we can use addEventListener
:
Making use of data-*
attributes
Adding data-*
attributes helps mapping element to its representation and handling:
Streamlining events with Event Delegation
Event delegation
is ideal when dealing with a large number of elements or dynamically added elements:
The dark corners — pitfalls and best practices
Keeps your 'this' in check
When using this
in an inline event handler, it's key to understand that it refers to the HTML element receiving the event.
Mind your syntax
Keep an eye out for typos or syntax errors that might hinder code execution. It's like checking the stage for banana peels before starting the concert.
Ditch the jQuery
In a world where every millisecond counts, go for vanilla JavaScript over jQuery. It’s like choosing acoustic over electric in an intimate jazz bar.
The right target audience
Make sure you're adding classes to the right element level for the visual output you're aiming for. Akin to choosing whether to mic the lead singer or the choir.
Was this article helpful?