How to Dynamically Load Dark Mode CSS with JavaScript

How to Dynamically Load Dark Mode CSS in your Website or WebApp (Ionic, React, or Angular):

1. Create the two separete css files, one for dark colors and one for bright
2. Upload those to your server to css folder
3. Use the script example below to load the appropriate css file based on the hours in the day.


function loadcssfile(filename, filetype){
    if (filetype=="css"){ //check filename is an external CSS file
        var fileref=document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref);
}

var date = new Date();

 if (date.getHours() >= 19 || date.getHours() <= 7) // after 7pm before 7am
	loadcssfile("../css/darkmode.css", "css");
 else
	loadcssfile("../css/lightmode.css", "css");

Don't blind your readers at night -_-

If you want to incorporate sunset and sunrise you can look into Suncal library, but you will have to request user's location which is always rude and not recommended.