We are still cooking the magic in the way!
jQuery & DOM Manipulation
CSS Classes & Styling
CSS Classes & Styling
jQuery provides powerful methods to manipulate CSS classes and styles dynamically, enabling you to create interactive and visually responsive web applications.
The .addClass() Method
The .addClass() method adds one or more classes to the matched elements.
HTML:
<div id="box">Click me</div> <button id="highlight-btn">Highlight</button>CSS:
.highlighted {
background-color: yellow;
border: 2px solid orange;
}
.large {
font-size: 24px;
}
.bold {
font-weight: bold;
}
JavaScript:
// Add single class
$("#highlight-btn").click(function() {
$("#box").addClass("highlighted");
});
// Add multiple classes (space-separated)
$("#box").addClass("large bold");
// Add classes one by one
$("#box").addClass("highlighted").addClass("large").addClass("bold");
The .removeClass() Method
The .removeClass() method removes one or more classes from the matched elements.
JavaScript:
// Remove single class
$("#box").removeClass("highlighted");
// Remove multiple classes
$("#box").removeClass("large bold");
// Remove all classes
$("#box").removeClass();
The .toggleClass() Method
The .toggleClass() method adds a class if it doesn't exist, or removes it if it does.
HTML:
<div id="panel">Content Panel</div> <button id="toggle-btn">Toggle Visibility</button>CSS:
.hidden {
display: none;
}
.active {
background-color: lightblue;
border-left: 4px solid blue;
}
JavaScript:
// Toggle single class
$("#toggle-btn").click(function() {
$("#panel").toggleClass("hidden");
});
// Toggle multiple classes
$("#panel").toggleClass("active highlighted");
// Toggle with boolean (second parameter)
var shouldShow = true;
$("#panel").toggleClass("hidden", !shouldShow);
Tip: The second parameter of
.toggleClass() acts as a switch. If true, the class is added; if false, it's removed. This is useful when you want to control the toggle behavior programmatically.
The .hasClass() Method
The .hasClass() method checks if any matched element has the specified class.
JavaScript:
// Check for class
if ($("#box").hasClass("highlighted")) {
console.log("Box is highlighted");
} else {
console.log("Box is not highlighted");
}
// Conditional styling
if (!$("#panel").hasClass("active")) {
$("#panel").addClass("active");
}
Using Callback Functions
Class methods can accept callback functions to add different classes based on index and current classes.
HTML:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
JavaScript:
// Add alternating classes
$("li").addClass(function(index) {
return index % 2 === 0 ? "even" : "odd";
});
// Toggle based on current state
$("li").toggleClass(function(index, currentClass) {
return currentClass.includes("active") ? "inactive" : "active";
});
The .css() Method
The .css() method gets or sets inline CSS styles on elements.
Getting CSS Values:
// Get single property
var color = $("#box").css("background-color");
console.log(color); // "rgb(255, 255, 0)"
var fontSize = $("#box").css("font-size");
console.log(fontSize); // "16px"
Setting CSS Values:
// Set single property
$("#box").css("color", "red");
// Set multiple properties (object syntax)
$("#box").css({
"background-color": "#f0f0f0",
"border": "2px solid #333",
"padding": "20px",
"border-radius": "10px"
});
// Using camelCase for multi-word properties
$("#box").css({
backgroundColor: "#f0f0f0",
borderRadius: "10px"
});
Best Practice: Prefer using
.addClass() and .removeClass() over .css() for styling. CSS classes are more maintainable and perform better. Use .css() for dynamic values that can't be predefined.
Dynamic Styling with Calculations
JavaScript:
// Set width based on calculation
var windowWidth = $(window).width();
$("#box").css("width", windowWidth * 0.5 + "px");
// Use callback for dynamic values
$("div.item").css("left", function(index) {
return (index * 100) + "px";
});
// Animate-like styling
var opacity = 0.5;
$("#box").css("opacity", opacity);
Practical Example: Interactive Theme Switcher
HTML:
<div id="app">
<header>
<h1>My Website</h1>
<div id="theme-controls">
<button class="theme-btn" data-theme="light">Light</button>
<button class="theme-btn" data-theme="dark">Dark</button>
<button class="theme-btn" data-theme="blue">Blue</button>
</div>
</header>
<main>
<p>Content goes here...</p>
</main>
</div>
CSS:
/* Default (light) theme */
#app {
background-color: #ffffff;
color: #333333;
}
/* Dark theme */
#app.theme-dark {
background-color: #1a1a1a;
color: #f0f0f0;
}
#app.theme-dark header {
background-color: #2d2d2d;
}
/* Blue theme */
#app.theme-blue {
background-color: #e3f2fd;
color: #0d47a1;
}
#app.theme-blue header {
background-color: #2196f3;
color: white;
}
.theme-btn.active {
background-color: #4caf50;
color: white;
}
JavaScript:
$(document).ready(function() {
// Load saved theme
var savedTheme = localStorage.getItem("theme") || "light";
applyTheme(savedTheme);
// Theme switcher
$(".theme-btn").click(function() {
var theme = $(this).data("theme");
applyTheme(theme);
// Save preference
localStorage.setItem("theme", theme);
});
function applyTheme(theme) {
// Remove all theme classes
$("#app").removeClass("theme-light theme-dark theme-blue");
// Add selected theme class
if (theme !== "light") {
$("#app").addClass("theme-" + theme);
}
// Update active button
$(".theme-btn").removeClass("active");
$(".theme-btn[data-theme='" + theme + "']").addClass("active");
}
});
Practical Example: Accordion Menu
HTML:
<div class="accordion">
<div class="accordion-item">
<div class="accordion-header">Section 1</div>
<div class="accordion-content">Content for section 1</div>
</div>
<div class="accordion-item">
<div class="accordion-header">Section 2</div>
<div class="accordion-content">Content for section 2</div>
</div>
<div class="accordion-item">
<div class="accordion-header">Section 3</div>
<div class="accordion-content">Content for section 3</div>
</div>
</div>
CSS:
.accordion-content {
display: none;
padding: 15px;
background-color: #f9f9f9;
}
.accordion-item.active .accordion-content {
display: block;
}
.accordion-header {
padding: 15px;
background-color: #4caf50;
color: white;
cursor: pointer;
}
.accordion-header:hover {
background-color: #45a049;
}
.accordion-item.active .accordion-header {
background-color: #388e3c;
}
JavaScript:
$(document).ready(function() {
$(".accordion-header").click(function() {
var item = $(this).parent();
// Close all other sections
$(".accordion-item").not(item).removeClass("active");
// Toggle current section
item.toggleClass("active");
});
});
Practical Example: Status Indicators
HTML:
<div class="user-list">
<div class="user" data-status="online">
<span class="status-indicator"></span>
<span>John Doe</span>
</div>
<div class="user" data-status="offline">
<span class="status-indicator"></span>
<span>Jane Smith</span>
</div>
<div class="user" data-status="away">
<span class="status-indicator"></span>
<span>Bob Johnson</span>
</div>
</div>
CSS:
.status-indicator {
display: inline-block;
width: 12px;
height: 12px;
border-radius: 50%;
margin-right: 8px;
}
.user[data-status="online"] .status-indicator {
background-color: #4caf50;
}
.user[data-status="offline"] .status-indicator {
background-color: #9e9e9e;
}
.user[data-status="away"] .status-indicator {
background-color: #ff9800;
}
JavaScript:
$(document).ready(function() {
// Update user status
function updateUserStatus(username, status) {
var user = $(".user").filter(function() {
return $(this).text().includes(username);
});
user.attr("data-status", status);
// Add temporary highlight
user.addClass("updated");
setTimeout(function() {
user.removeClass("updated");
}, 1000);
}
// Simulate status changes
setInterval(function() {
var statuses = ["online", "offline", "away"];
var randomStatus = statuses[Math.floor(Math.random() * statuses.length)];
updateUserStatus("John Doe", randomStatus);
}, 5000);
});
Performance Considerations
Good Practice:
// Add multiple classes at once (better)
$("#box").addClass("class1 class2 class3");
// Chain operations (better)
$("#box").addClass("highlighted").css("opacity", 0.8).show();
// Use CSS classes instead of inline styles (best)
// Bad:
$("#box").css("color", "red").css("font-size", "20px");
// Good:
$("#box").addClass("styled-box");
/* .styled-box { color: red; font-size: 20px; } */
Exercise:
- Create a todo list where each item can be marked as complete, important, or deleted
- Use
.addClass()to add a "completed" class (strikethrough text) when clicking on an item - Add a star icon that toggles an "important" class (highlighted background) when clicked
- Add a delete button that adds a "deleted" class (fade out) before removing the item
- Add filter buttons (All, Active, Completed) that show/hide items based on their classes
- Style each state differently using CSS classes
Summary
.addClass(classes)- Add one or more classes.removeClass(classes)- Remove one or more classes.toggleClass(classes)- Toggle classes on/off.hasClass(class)- Check if element has a class.css(property)- Get CSS value.css(property, value)- Set inline CSS.css(object)- Set multiple CSS properties- Prefer CSS classes over inline styles for maintainability
- Use callback functions for index-based class assignment
- Chain methods for better performance