Telerik blogs

Give your users a way to ease their eye strain or just set their preferences with this easy installation of a dark/light mode switch.

Digitally painted mountains with Telerik logo and Blazor logo
Image created with Leonardo.ai

In this post, I’ll demonstrate how to create a day/night (dark mode) button to add to your Blazor applications that automatically sets up according to the environment and changes when the user updates the mode on the environment.

The Importance of Dark Mode

Dark mode has grown in popularity across various digital platforms and apps, and for good reason. Its use goes beyond mere aesthetics—it may also have health advantages, notably for the eyes.

One of the primary advantages of dark mode is that it helps lessen eye strain, especially in low light or at night. The darker color palette minimizes the quantity of light emitted by the screen, reducing the total brightness to which your eyes are subjected. It may help alleviate symptoms linked with extended screen usage, such as headaches, dry eyes and blurred vision, called Computer Vision Syndrome or Digital Eye Strain.

Furthermore, dark mode may increase text legibility, resulting in a better user experience. High-contrast text and images, such as white writing on a black background, may be easier to read for specific individuals, decreasing eye strain.

Another significant benefit is improved sleep quality. Bright blue light, especially late at night, may disrupt your circadian rhythm or your body’s sleep-wake cycle. This is because blue light inhibits the generation of melatonin, a hormone that aids in regulating sleep. You may decrease this impact by adopting dark mode, particularly in the evening, perhaps enhancing sleep quality.

However, it is crucial to remember that dark mode is not a one-size-fits-all solution. While it has many advantages, it may not be ideal or pleasant for everyone, especially those with specific visual impairments or in areas with high ambient light, where dark mode might cause strain.

Regardless, the popularity of dark mode demonstrates how developers are working to create a more pleasant and healthy digital environment. It’s simply one more tool in an extensive toolbox aimed at improving and sustaining our connection with technology.

A Sample That Automatically Changes Mode According to the Environment

Follow these steps:

  1. Create your Progress Telerik UI for Blazor app.
  2. Add this code to the Index.html:
<!-- Theme switching start -->
<link  id="TelerikThemeLink"  href="https://blazor.cdn.telerik.com/blazor/4.4.0/kendo-theme-default/swatches/default-main.css"  rel="stylesheet"  type="text/css" />
<script  src="ThemeChanger.js"></script>
<!-- Theme switching end -->

You can choose the themes you like. See the references at the end of this post.

  1. Create the file ThemeChanger.js and add it to the wwwroot:
// this code is in the ~/wwwroot/ThemeChanger.js file

var themeChanger = {

  firstRender: function () {
    window.matchMedia((prefers-color-scheme: light)).addEventListener(‘change’, event => {
      themeChanger.changeCss(true);
    });
  }
  ,
  changeCss: function (auto) {

    var darkTheme = "https://blazor.cdn.telerik.com/blazor/4.4.0/kendo-theme-default/swatches/default-main-dark.css";
    var dayTheme = "https://blazor.cdn.telerik.com/blazor/4.4.0/kendo-theme-default/swatches/default-main.css";

    var oldLink = document.getElementById("TelerikThemeLink");

    var newTheme = darkTheme;
    
    if (auto) {
      
      newTheme = (window.matchMedia && window.matchMedia((prefers-color-scheme: dark)).matches)
        ? darkTheme
        : dayTheme;
    }
    else {
    
      if (darkTheme === oldLink.getAttribute("href")) {
        newTheme = dayTheme;
      }
    }
    
    var newLink = document.createElement("link");
    newLink.setAttribute("id", "TelerikThemeLink");
    newLink.setAttribute("rel", "stylesheet");
    newLink.setAttribute("type", "text/css");
    newLink.setAttribute("href", newTheme);
    newLink.onload = () => {
      oldLink.parentElement.removeChild(oldLink);
    };
    
    document.getElementsByTagName("head")[0].appendChild(newLink);
  }
}
  1. Add this to the Index.razor or in a component:
@inject IJSRuntime JsInterop

<TelerikButton OnClick="ChangeTheme">Day/Night(Dark Mode)</TelerikButton>

@code {

  protected  override  async Task OnAfterRenderAsync(bool firstRender)
  {
    if (firstRender)
    {
      await JsInterop.InvokeVoidAsync("themeChanger.changeCss", true);
      await JsInterop.InvokeVoidAsync("themeChanger.firstRender");
    }
  }
  
  async Task ChangeTheme()
  {
    await JsInterop.InvokeVoidAsync("themeChanger.changeCss", false);
  }
}

Voilá! The magic is done!

Here is the result:

Overlapped screens showing dark mode and light mode

Now when altering the mode on Windows, the theme will automatically change:

Dropdown will allow you to set dark or light mode

Conclusion

The value of dark mode in maintaining eye health cannot be overemphasized. Developers can consider including this functionality in their apps to enhance the user experience and encourage digital well-being. Implementing dark mode has never been simpler, thanks to technologies like Blazor and Telerik.

Telerik UI for Blazor includes over 100+ native components, including a fully flexible and easy-to-use dark theme. As a result, your application may deliver a soothing user experience at night or in low-light circumstances, reducing eye strain and perhaps enhancing sleep quality for your users.

Download and try out the demonstration of the Telerik-powered dark mode functionality in Blazor. Even if you’re using a trial version of Telerik UI for Blazor, the legendary support team is standing by to help you with any issues. Let’s work together to make the digital environment more pleasant and healthy for all users. Your input will be important in Progress Telerik’s ongoing efforts to improve and optimize the dark mode functionality.

Try Telerik UI for Blazor

References


About the Author

Jefferson S. Motta

Jefferson S. Motta is a senior software developer, IT consultant and system analyst from Brazil, developing in the .NET platform since 2011. Creator of www.Advocati.NET, since 1997, a CRM for Brazilian Law Firms. He enjoys being with family and petting his cats in his free time. You can follow him on LinkedIn and GitHub.

Related Posts

Comments

Comments are disabled in preview mode.