The Custom Theme Switcher is a JavaScript script that enables users to switch between light and dark themes on a webpage. It provides a toggle button and allows for theme changes triggered by user interactions or programmatically.
Toggle Button
- A button with the attribute theme="toggle"
is provided for users to switch between light and dark themes.
Default Theme
- The default theme is set to "light" unless specified otherwise using the default
attribute on the toggle button.
Theme Application to Elements
- The script applies the selected theme to elements with the class "theme."
- Elements can have specific styling for both light and dark themes.
Event Handling
- The script triggers a callback function when the theme changes, providing the current theme as an argument to the callback.
theme="toggle"
to enable theme switching. <button theme="toggle" default="light">Toggle Theme</button>
<body class='theme'>
<h>This is a paragraph</h>
<article>
Something written here
</article>
</body>
$theme.themeSet("dark")
to programmatically change the theme.javascript
$theme.themeSet("dark");
The themeSet
method is used to programmatically set the theme of the webpage. It accepts the following options:
$theme.themeSet("dark");
$theme.themeSet("light");
$theme.themeSet("default");
$theme.change
to be notified when the theme changes. $theme.change(function (currentTheme) {
console.log("Current theme:", currentTheme);
});
The currentTheme
value can be a string ("dark"
, "light"
), undefined
(if no theme is set), or false
(if there's an issue).
Ensure that the appropriate styles for light and dark themes are defined in the <style>
section of the document.
<style>
.dark {
background: black;
color: white;
}
/* ... other styles ... */
</style>
The class='theme'
attribute is essential for associating specific elements with the theme-switching functionality.
Ensure that the styles for light and dark themes are appropriately defined in the document to achieve the desired visual changes.
You can customize the styles within the .dark
class to match the visual design of your dark theme.