Setting Up a Theme Toggle Button
In this lesson, we will analyze a button to toggle between light and dark themes.
Introduction to the data-theme
Attribute
The data-*
attribute is a custom data attribute introduced in HTML5. It allows you to store additional information on HTML elements.
In this example, the data-theme
attribute is used to manage the overall theme of the webpage.
This attribute can be used in CSS selectors and JavaScript to retrieve or modify the theme state.
HTML Structure for Dark and Light Buttons
Define buttons in HTML to switch themes. Each button is created with an <a>
tag, each with a specific id (dark
and light
) to differentiate the actions for each theme.
<ul class="menu">
<a id="dark" class="btn"> <i class="icon icon-left ion-md-moon"></i> Dark </a>
<a id="light" class="btn">
<i class="icon icon-left ion-md-sunny"></i> Light
</a>
</ul>
Icon and Text Placement
Each theme button consists of an icon (<i>
) and text (Dark
or Light
).
The icons are fetched from an external resource called Ionicons, and the icons are displayed using the class names for each icon.
Since the icons and text are placed in the same line, users can easily distinguish the state of the theme.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.