The best way to change design with jQuery is to switch CSS classes — keep the styles in CSS.
| Method | Does |
|---|---|
.addClass('active') |
add a class |
.removeClass('active') |
remove a class |
.toggleClass('active') |
add or remove |
.hasClass('active') |
check (true / false) |
Several classes: .addClass('card shadow').
Active menu pattern
$('.tab').click(function () {
$('.tab').removeClass('active');
$(this).addClass('active');
});
Toggle with a condition
.toggleClass('dark', isNight) — add when true, remove when false.
Example
Example β Active menu and dark mode
HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
body { transition: background .3s, color .3s; font-family: Arial, sans-serif; }
body.dark { background: #1e1e1e; color: #eee; }
.menu a { display:inline-block; padding:8px 14px; text-decoration:none; color:inherit; border-radius:6px; }
.menu a.active { background:#1f386b; color:#fff; }
</style>
<nav class="menu">
<a href="#" class="active">Home</a>
<a href="#">Tutorials</a>
<a href="#">Exams</a>
</nav>
<p><button id="theme">π Dark mode</button></p>
<script>
$(function () {
$('.menu a').click(function (e) {
e.preventDefault();
$('.menu a').removeClass('active');
$(this).addClass('active');
});
$('#theme').click(function () {
$('body').toggleClass('dark');
$(this).text($('body').hasClass('dark') ? 'βοΈ Light mode' : 'π Dark mode');
});
});
</script>