DEV Community

Cover image for Set the theme of a website based on the time of the day (no external library)
Sam
Sam

Posted on • Originally published at blog.dotenx.com

Set the theme of a website based on the time of the day (no external library)

In this blog post, I will show you how to use JavaScript, and CSS to set the theme of your website based on the time of day. This can be a useful feature if you want to create a website that automatically switches between a light and dark theme based on the time of day. By the end of this post, you will have a website that automatically changes its appearance based on the time of day, creating a more dynamic and engaging user experience.

Before we move on, remember you can implement your websites or landing pages with or without coding on DoTenX for free. Make sure to check it out and even nominate your work to be showcased there as well.


First, we will create two CSS stylesheets, one for the light theme and one for the dark theme. These stylesheets will define the colours and other styles that will be used on the website.

/* light.css */

body {
  background-color: white;
  color: black;
}

/* dark.css */

body {
  background-color: black;
  color: white;
}
Enter fullscreen mode Exit fullscreen mode

Next, we will use JavaScript to detect the current time of day and apply the appropriate stylesheet to the element of the HTML page.

<!DOCTYPE html>
<html>
<head>
  <title>Time-Based Theme Example</title>

  <script>
    // Get the current time
    var date = new Date();
    var hour = date.getHours();

    // Apply the light or dark stylesheet based on the time of day
    if (hour >= 6 && hour < 18) {
      // If the time is between 6am and 6pm, use the light theme
      var link = document.createElement("link");
      link.setAttribute("rel", "stylesheet");
      link.setAttribute("type", "text/css");
      link.setAttribute("href", "light.css");
      document.head.appendChild(link);
    } else {
      // Otherwise, use the dark theme
      var link = document.createElement("link");
      link.setAttribute("rel", "stylesheet");
      link.setAttribute("type", "text/css");
      link.setAttribute("href", "dark.css");
      document.head.appendChild(link);
    }
  </script>
</head>
<body>
  <h1>Time-Based Theme Example</h1>
  <p>This page demonstrates how to use JavaScript, HTML, and CSS to set the theme of a website based on the time of day.</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this example, we use the Date object in JavaScript to get the current time, and then we use an if statement to determine whether the time is between 6am and 6pm. If it is, we apply the light theme stylesheet, and if it is not, we apply the dark theme stylesheet.

You can adjust the times and styles to suit your needs, and you can also use additional stylesheets and JavaScript code to create more complex and sophisticated themes for your website.

Top comments (17)

Collapse
 
brampayrequest profile image
Bram Hammer

Honestly don't think this is a good example.
Better to set a class to your body (or use a dataset attribute on the html or body tag) and set variables in CSS and change them when data-theme="dark" or data-theme="light" for example.

Make the default light, and when hours are before 6 or after 18... --> Set to dark.

:root, html[data-theme='light'] {
    --background-color: white;
    --text-color: black;
}

html[data-theme='dark'] {
    --background-color: black;
    --text-color: white;
}

body {
    background: var(--background-color);
    color: var(--text-color);
}
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html data-theme="light">
<head>
  <title>Time-Based Theme Example</title>
  <script>
    // Get the date
    const date = new Date();
    const hour = date.getHours();

    // Change data-theme to dark based on the time of day
    if (hour < 6 || hour >= 18) 
      document.documentElement.dataset.theme = 'dark';
  </script>
</head>
<body>
  <h1>Time-Based Theme Example</h1>
  <p>This page demonstrates how to use JavaScript, HTML, and CSS to set the theme of a website based on the time of day.</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rgolawski profile image
Rafał Goławski

Exactly this ā˜ Using prefers-color-scheme this could be solved in a few lines of CSS.

@media (prefers-color-scheme: light) {
  /* light scheme styles */
}

@media (prefers-color-scheme: dark) {
  /* dark scheme styles */
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mohsenkamrani profile image
Sam

Thanks for the addition. This example is definitely a good approach. Please take a look at my reply.

Collapse
 
mohsenkamrani profile image
Sam

This is just a different approach which potentially saves you a tiny bit of bandwidth by not importing the styles you don't use. More importantly it's a good example, IMO, to show how to conditionally include the styles you need.

Collapse
 
amircahyadi profile image
Amir-cahyadi

ā¤ļøšŸ‘šŸ‘

Collapse
 
sbouwnsv profile image
Sukhman

Interesting

Collapse
 
ignore_you profile image
Alex

I really don't want to sound toxic and I hope that you won't take it to heart. Anyway, when I clicked on the link from dev.to email, my thoughts were like "wow it should be very interesting". How did they solve daylight saving time? Timezones? Different latitudes that affect day length? That shoulda be hell of an interesing, is there some new API? Well...

Collapse
 
unnamedplayr profile image
Ian M

I happened to run into this the other day, here's some javascript to determine sunrise/sunset based on latitude and longitude: github.com/udivankin/sunrise-sunset

Collapse
 
mohsenkamrani profile image
Sam

Sorry to disappoint, but I didn't have any bad intentions. I think you missed the beginners tag.
I use the tags accordingly so you know what you can expect from the article.

Collapse
 
nazaroni profile image
Nazar

same there šŸ¤£ šŸ˜… šŸ„²

Collapse
 
mohsenkamrani profile image
Sam

Just repeating the above reply:
Sorry to disappoint, but I didn't have any bad intentions. I think you missed the beginners tag.
I use the tags accordingly so you know what you can expect from the article.

Collapse
 
sip profile image
Dom Sipowicz

Dark mode is a first-class feature of many operating systems.

The class strategy can be used to support both the userā€™s system preference or a manually selected mode by using the Window.matchMedia() API.

Collapse
 
kevgk profile image
Kevin G.

So you want to duplicate all your color related styles?
How about using css custom properties?

Collapse
 
jak2k profile image
Jak2k

I think it's a bad idea. Users can configure such things in their system settings and when they do, we should stick to the user's decisions.

Collapse
 
dyn0987 profile image
dyn0987

Pretty sure this post is meant for beginners to learn js. I think its a good idea

Collapse
 
kolja profile image
Kolja

You will be free to add a toggle button šŸ˜‰

Collapse
 
lotfijb profile image
Lotfi Jebali

I ddidn't think about this, good one
But I prefer you write it in a seperate js file to keep html code clean.
Thank you for sharing