Add and Remove Class on Mouseover Using JavaScript (CodePen)
This article will guide you through adding and removing classes to HTML elements using JavaScript, specifically on mouseover events. We'll be using CodePen for a hands-on demonstration.
Understanding the Basics
The core concept here is to manipulate the class attribute of an HTML element using JavaScript. We'll use the mouseover
and mouseout
events to trigger the addition and removal of the desired class.
Steps involved:
- HTML Structure: We'll create a simple HTML element (in this case, a
<div>
) to work with. - CSS Styling: We'll add some basic CSS styles to visually differentiate the element when the class is applied.
- JavaScript Code: We'll write JavaScript code to handle the mouseover and mouseout events, adding and removing the class respectively.
CodePen Implementation
Let's break down the code:
HTML (index.html):
Add & Remove Class on Mouseover
Hover me!
CSS (style.css):
.container {
background-color: #eee;
padding: 20px;
border-radius: 5px;
cursor: pointer; /* Indicate interactivity */
}
.container.hovered {
background-color: #ddd;
transform: scale(1.1); /* Add a slight zoom effect */
}
JavaScript (script.js):
const container = document.querySelector('.container');
container.addEventListener('mouseover', () => {
container.classList.add('hovered');
});
container.addEventListener('mouseout', () => {
container.classList.remove('hovered');
});
Explanation:
- HTML: We have a simple
<div>
with the class "container". - CSS: We define styles for the
.container
class (default appearance) and.container.hovered
class (hovered appearance). - JavaScript:
- We select the element using
document.querySelector('.container')
. - We add event listeners for
mouseover
andmouseout
events. - Inside the event listeners, we use
classList.add()
andclassList.remove()
to toggle the "hovered" class on the element.
- We select the element using
Running the CodePen
- Go to CodePen: Open your browser and navigate to .
- Create a New Pen: Click "New Pen" to start a new project.
- Paste the Code: Paste the HTML, CSS, and JavaScript code into their respective sections in CodePen.
- Run the Code: Press the "Run" button to see your code in action.
Conclusion
This simple demonstration showcases how to dynamically add and remove classes using JavaScript, allowing you to control the appearance and behavior of HTML elements based on user interaction. This technique is fundamental for creating interactive web interfaces and enhancing user experiences.