Duke
Duke

Reputation: 81

How to overwrite CSS color scheme settings

In HTML. Now I know we can ask CSS to do something when user change their system color scheme, like

@media (prefers-color-scheme: dark)

But what if I want to overwrite that setting like I need light color scheme at night, but I don’t want to change my system color scheme settings, is there any JavaScript or jQuery way to fool CSS (to proceed the dark park even when system is light, or opposite ), so I can switch webpage color scheme by click some element?

Upvotes: 1

Views: 659

Answers (1)

Gosi
Gosi

Reputation: 2003

You should first get the current time in 24 hour format like so:

var dayNight = (new Date()).getHours();

Now, you most probably have 2 classes with background color, 1 for day and 1 for night.

So, you can use if/else statement to decide when you want to add or remove a class using JQuery.

So in my example, when the .dayNight is bigger or equals to 7 (7am) and lesser than 19 (7pm), it adds the .day class and removes the .night class.

And when the .dayNight is bigger or equals to 0 (12 midnight) AND if it is smaller than 7 (7am), it adds the .night class and removes the .day class.

Also, when it is bigger or equals to 19 (7pm) and equals or lesser than 23 (11pm) it does the same above. We've already assigned 0 (12 midnight) in the above code, so we can set it to 23 (11pm) here.

Try this:

var dayNight = (new Date()).getHours();

if(dayNight>=7 && dayNight < 19) {
  $( "#display" ).removeClass( "night" ).addClass( "day" );
}

if((dayNight>=0 && dayNight<7) || (dayNight>=19 && dayNight <=23)) {
	$( "#display" ).removeClass( "day" ).addClass( "night" );
}
.day {
  background-color: blue;
  color: white;
}

.night {
  background-color: red;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="display">
Hello!
</div>

Upvotes: 2

Related Questions