In this tutorial, we will learn how to switch between different themes dynamically on a web page. This feature will allow users to customize their view according to their preferences and improve their overall user experience.
By the end of this tutorial, you will be able to:
Prerequisites:
Basic understanding of HTML, CSS, and JavaScript is required to follow along with this tutorial.
To implement dynamic theme switching, we need different CSS files for each theme. We'll use JavaScript to switch between these CSS files based on user input. We'll also use localStorage to store the user's theme preference and load it on subsequent visits.
<!-- HTML -->
<div id="themeSwitcher">
<button onclick="switchTheme('dark')">Dark Theme</button>
<button onclick="switchTheme('light')">Light Theme</button>
</div>
/* CSS */
body.dark {
background-color: black;
color: white;
}
body.light {
background-color: white;
color: black;
}
// JavaScript
function switchTheme(theme) {
document.body.className = theme;
}
In this example, we have two buttons that call the switchTheme
function with a different argument. This function changes the className
of the body
element, which switches the theme.
// JavaScript
function switchTheme(theme) {
document.body.className = theme;
localStorage.setItem('theme', theme);
}
window.onload = function() {
var theme = localStorage.getItem('theme');
if (theme) switchTheme(theme);
}
In this example, we use localStorage.setItem
to store the user's theme preference. When the page loads, we use localStorage.getItem
to retrieve the stored theme and apply it by calling switchTheme
.
In this tutorial, we learned how to switch between different themes dynamically using JavaScript, CSS, and HTML. We also learned how to store the user's theme preference using localStorage and apply it on subsequent visits.
Next steps for learning would be to explore more about localStorage and how to create more complex themes using CSS.
Some additional resources are:
Exercise 1: Create a webpage with 3 different themes and implement theme switching.
Exercise 2: Store the user's theme preference and apply it on subsequent visits.
Exercise 3: Add a feature to automatically switch to a 'night' theme based on the user's local time.
Solutions:
You can follow the code examples provided in this tutorial to create 3 different themes and implement theme switching.
Use localStorage.setItem
to store the theme preference and localStorage.getItem
to retrieve and apply it.
Use the Date
object to get the current hour and switch to a 'night' theme if the hour is after 6 PM.
Tips for further practice: Try to create more complex themes and implement transition effects when switching themes.