The simple tricks to change your website theme based on day and night

LakshmananLakshmanan
1 min read

Hi everyone, every website have a theme options. so, a website user able to choose their preferred theme like dark, light..etc., This is existing followed approach in everyone website.

how is it (we show the website theme based on the user day and night). I just tried. if you like it use in your website. give some different experience to your website user.

Let's jump into the implementation part:

For now, I take a simple coming soon html template for with dark and light theme.

{% codepen https://codepen.io/explore-free-projects/pen/zYZvewO %}

The above page theme change based on body attribute data-theme: "dark-theme" / "light-theme".

by default show light-theme.

Now, coming to main point how we change website theme based on day and night.

function setThemePreference() {
  var d = new Date();
  /*
  * The getHours() method returns the hour (from 0 to 23) of the specified date and time.
  * Day = 0 - 11
  * Night = 12 - 23
  */
  var currentHour = d.getHours();

  /*
  * The dark theme load early morning and night
  * The light theme load morning and evening
  */

  if(currentHour >= 19 || currentHour <= 6) {
    document.body.setAttribute("data-theme", "dark_theme") 
  }else {
    document.body.setAttribute("data-theme", "light_theme") 
  }
}

window.onload = setThemePreference;

That's all.

The workable version of the codepen URL

0
Subscribe to my newsletter

Read articles from Lakshmanan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Lakshmanan
Lakshmanan

Greetings! I'm thrilled to share my journey as a frontend developer, where my dedication to creating memorable web experiences has been the driving force behind my success. With a career spanning over several years in the dynamic world of web development, I've developed a profound love for crafting pixel-perfect and intuitive user interfaces. My journey began with mastering the essentials of HTML, CSS, and JavaScript, and it has evolved into embracing modern frontend frameworks like React and GraphQL to build dynamic, interactive, and user-centric applications. I'm excited to connect with fellow developers, designers, and enthusiasts to exchange ideas and collaborate on innovative projects. Feel free to reach out to me via LinkedIn. Let's create unforgettable web experiences together! Thank you for visiting my profile, and I look forward to exploring new frontiers in web development with you!