Manipulating CSS with JavaScript (Adding & Removing Classes)
Introduction
CSS provides styles to HTML elements, but sometimes, you need to dynamically change styles based on user interactions, animations, or conditions. JavaScript allows you to manipulate CSS in various ways, including adding and removing classes dynamically.
This lesson will cover:
Why use JavaScript for CSS manipulation?
Different ways to modify CSS using JavaScript
Adding and removing classes dynamically
Real-world examples
Best practices
Why Use JavaScript for CSS Manipulation?
Using JavaScript to change styles dynamically allows:
Interactive elements (e.g., highlighting a button when clicked).
Theming support (e.g., switching between dark mode and light mode).
Animations and transitions (e.g., toggling a menu).
Dynamic layout adjustments (e.g., making elements sticky or responsive).
Ways to Modify CSS with JavaScript
There are three common ways to modify CSS using JavaScript:
1. Changing Inline Styles
You can directly change the style property of an element.
document.getElementById("myDiv").style.color = "red";
Drawbacks:
Overwrites existing inline styles.
Not ideal for large-scale styling.
2. Modifying CSS Stylesheets
You can access and modify styles in a CSS file.
document.styleSheets[0].cssRules[0].style.backgroundColor = "blue";
Drawbacks:
More complex than class manipulation.
Hard to manage dynamically.
3. Adding & Removing Classes (Recommended)
A better approach is to use classList to add, remove, or toggle CSS classes dynamically.
Manipulating Classes Using JavaScript
1. classList.add() – Adding a Class
This method adds a new class to an element.
Example: Highlight a button when clicked
<button id="myButton">Click Me</button>
<style>
.highlight {
background-color: yellow;
color: black;
}
</style>
<script>
document.getElementById("myButton").addEventListener("click", function() {
this.classList.add("highlight");
});
</script>
Explanation:
When the button is clicked, the .highlight class is added.
2. classList.remove() – Removing a Class
This method removes a class from an element.
Example: Remove a highlight after clicking again
<button id="myButton">Click Me</button>
<style>
.highlight {
background-color: yellow;
color: black;
}
</style>
<script>
document.getElementById("myButton").addEventListener("click", function() {
this.classList.remove("highlight");
});
</script>
Explanation:
Clicking the button removes the .highlight class.
3. classList.toggle() – Adding & Removing a Class Dynamically
This method adds a class if it doesn’t exist and removes it if it does.
Example: Toggle Dark Mode
<button id="toggleTheme">Toggle Theme</button>
<style>
body.dark-mode {
background-color: black;
color: white;
}
</style>
<script>
document.getElementById("toggleTheme").addEventListener("click", function() {
document.body.classList.toggle("dark-mode");
});
</script>
Explanation:
When the button is clicked, dark-mode is added if missing or removed if present.
4. classList.contains() – Checking if an Element Has a Class
This method checks if a class exists.
Example: Check if a button has a class before removing it
let button = document.getElementById("myButton");
if (button.classList.contains("highlight")) {
button.classList.remove("highlight");
}
Explanation:
Ensures that the class is removed only if it is present.
5. classList.replace() – Replacing a Class
This method replaces one class with another.
Example: Change a button's style on hover
<button id="myButton" class="blue">Hover Me</button>
<style>
.blue {
background-color: blue;
color: white;
}
.red {
background-color: red;
color: white;
}
</style>
<script>
let button = document.getElementById("myButton");
button.addEventListener("mouseenter", function() {
this.classList.replace("blue", "red");
});
button.addEventListener("mouseleave", function() {
this.classList.replace("red", "blue");
});
</script>
Explanation:
When hovering, the button changes from blue to red and back.
Real-World Use Cases
Navbar Toggle on Mobile
Show/hide the menu when clicking a button.
Form Validation
Add a red border to invalid inputs.
Popup Modal
Add/remove a class to show or hide a modal.
Theming (Dark Mode)
Toggle dark mode with a single button click.
Best Practices
Use CSS classes instead of inline styles for maintainability.
Use classList.toggle() when possible for cleaner code.
Check for class existence (classList.contains()) before removing a class.
Avoid modifying stylesheets directly unless necessary.
Conclusion
Manipulating CSS using JavaScript is a powerful way to create interactive elements, themes, and animations. The best approach is to use classList methods (add, remove, toggle, contains, and replace) for cleaner, maintainable, and reusable code.
Would you like to see more complex examples, such as animations or responsive design toggles?
Advanced CSS Manipulation with JavaScript 🚀
Now that you understand basic class manipulation, let’s move on to more advanced examples like:
Animated Navbar Toggle
Smooth Dark Mode Transition
Show/Hide Elements with Fade Effects
Scroll-based Animations
Responsive Design Toggling
1. Animated Navbar Toggle (Mobile Menu)
On mobile, a navbar menu is usually hidden and appears when clicking a button.
Example: Slide-in Navbar
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Navbar Toggle</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.navbar {
background: #333;
padding: 10px;
color: white;
text-align: center;
}
.menu {
position: fixed;
left: -250px;
top: 0;
width: 250px;
height: 100%;
background: #222;
transition: 0.5s;
padding-top: 60px;
}
.menu a {
display: block;
color: white;
padding: 15px;
text-decoration: none;
transition: 0.3s;
}
.menu a:hover {
background: #575757;
}
.menu.active {
left: 0;
}
.menu-button {
background: #ff9800;
padding: 10px 20px;
cursor: pointer;
border: none;
color: white;
font-size: 18px;
margin: 10px;
}
</style>
</head>
<body>
<div class="navbar">
<button class="menu-button" id="toggleMenu">☰ Open Menu</button>
</div>
<div class="menu" id="menu">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Contact</a>
</div>
<script>
document.getElementById("toggleMenu").addEventListener("click", function() {
document.getElementById("menu").classList.toggle("active");
});
</script>
</body>
</html>
How it Works:
The menu starts off-screen (left: -250px).
Clicking the button toggles the active class, which brings the menu into view (left: 0).
2. Smooth Dark Mode Transition
Let’s improve dark mode with a smooth transition effect.
Example: Dark Mode with Fade Effect
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dark Mode</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
transition: background 0.5s, color 0.5s;
}
.dark-mode {
background: black;
color: white;
}
.toggle-btn {
padding: 10px 20px;
font-size: 18px;
cursor: pointer;
background: #007BFF;
color: white;
border: none;
border-radius: 5px;
}
</style>
</head>
<body>
<button class="toggle-btn" id="toggleDarkMode">Toggle Dark Mode</button>
<script>
document.getElementById("toggleDarkMode").addEventListener("click", function() {
document.body.classList.toggle("dark-mode");
});
</script>
</body>
</html>
How it Works:
The transition makes the background and text fade smoothly into dark mode.
classList.toggle("dark-mode") switches between light and dark themes.
3. Show/Hide Elements with Fade Effect
Instead of instantly showing and hiding elements, let’s use fade-in and fade-out animations.
Example: Click to Show/Hide a Message
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fade In/Out</title>
<style>
.message {
opacity: 0;
visibility: hidden;
transition: opacity 0.5s, visibility 0.5s;
}
.message.show {
opacity: 1;
visibility: visible;
}
</style>
</head>
<body>
<button id="toggleMessage">Show Message</button>
<p class="message" id="message">Hello! This is a fade-in message.</p>
<script>
document.getElementById("toggleMessage").addEventListener("click", function() {
document.getElementById("message").classList.toggle("show");
});
</script>
</body>
</html>
How it Works:
.message starts hidden (opacity: 0, visibility: hidden).
.show makes it fade in.
Clicking the button toggles visibility with a smooth effect.
4. Scroll-Based Animations
We can apply styles dynamically when the user scrolls.
Example: Fade-in Sections on Scroll
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scroll Animation</title>
<style>
.section {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
opacity: 0;
transform: translateY(50px);
transition: opacity 0.5s, transform 0.5s;
}
.section.visible {
opacity: 1;
transform: translateY(0);
}
</style>
</head>
<body>
<div class="section">Scroll Down 👇</div>
<div class="section">This appears when scrolled.</div>
<div class="section">More content...</div>
<script>
function revealSections() {
let sections = document.querySelectorAll(".section");
sections.forEach((section) => {
let rect = section.getBoundingClientRect();
if (rect.top < window.innerHeight - 100) {
section.classList.add("visible");
}
});
}
window.addEventListener("scroll", revealSections);
revealSections();
</script>
</body>
</html>
How it Works:
Sections are invisible at first.
As you scroll down, JavaScript checks if they are inside the viewport and then applies the .visible class, making them fade in.
5. Responsive Design: Toggle Grid/List View
A grid layout can switch to a list layout dynamically.
Example: Switch Between Grid & List
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grid/List Toggle</title>
<style>
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 10px;
transition: 0.3s;
}
.container.list {
display: block;
}
.item {
background: lightblue;
padding: 20px;
text-align: center;
border-radius: 5px;
}
</style>
</head>
<body>
<button id="toggleView">Toggle Grid/List</button>
<div class="container" id="content">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
<script>
document.getElementById("toggleView").addEventListener("click", function() {
document.getElementById("content").classList.toggle("list");
});
</script>
</body>
</html>
Switches between a grid and list layout dynamically! 🎉
Final Thoughts
Now you can: ✅ Animate menus
✅ Smoothly toggle dark mode
✅ Use fade effects
✅ Animate elements on scroll
✅ Toggle responsive layouts
Want a real project demo? Let me know! 🚀
Contact us for software training, education or development
Varanasi Software Junction: Contacting Varanasi Software Junction for online and offline classes