Many website visitors prefer to switch between light and dark modes for better readability and comfort. Adding a toggle for this feature to your Jekyll site can enhance user experience and accessibility. In this article, we will explore how to implement a simple light/dark mode toggle using JavaScript and CSS.
Understanding the Basics
Before we begin, it's important to understand that a light/dark mode toggle involves changing the website's color scheme dynamically. This can be achieved by toggling a CSS class on the body element, which then switches between predefined styles.
Step-by-Step Implementation
1. Define CSS Styles
Start by adding CSS styles for both light and dark modes. You can include these styles in your _includes or directly within your HTML <style> tags.
Example CSS:
body { transition: background-color 0.3s, color 0.3s; }
body.light-mode { background-color: #ffffff; color: #000000; }
body.dark-mode { background-color: #222222; color: #ffffff; }
2. Add the Toggle Button
Insert a button in your layout where users can click to switch modes. For example:
<button id="mode-toggle">Switch Mode</button>
3. Implement JavaScript
Add a script to handle the toggle action. You can include this at the bottom of your layout or in a separate JavaScript file.
Additional Tips
To improve user experience, consider saving the user's preferred mode using localStorage. This way, the mode persists across page reloads.
Example enhancement:
Conclusion
Adding a light/dark mode toggle to your Jekyll site is straightforward with CSS, JavaScript, and a bit of customization. This feature can make your website more user-friendly and modern. Experiment with styles and functionalities to best suit your site's design and your visitors' preferences.