CSS Changing upon time.

Kristopher

Photographer
Dec 25, 2010
803
68
So I have this JS script that's supposed to change the CSS based upon the time the client is at.

So basically I have this:

Code:
<script>

function getStylesheet() {
      var currentTime = new Date().getHours();
      if (0 <= currentTime&&currentTime < 5) {
       document.write("<link rel='stylesheet' href='stylenight.css' type='text/css'>");
      }
      if (5 <= currentTime&&currentTime < 18) {
       document.write("<link rel='stylesheet' href='styleday.css' type='text/css'>");
      }
      if (18 <= currentTime&&currentTime < 24) {
       document.write("<link rel='stylesheet' href='stylenight.css' type='text/css'>");
      }
}

getStylesheet();

</script>

<noscript><link href="style.css" rel="stylesheet"></noscript>
I've added it to the test page and so far its not loading up anything besides the HTML. Anyone have a idea?
 

RastaLulz

fight teh power
Staff member
May 3, 2010
3,935
3,936
With jQuery, this is how you'd do it:
Code:
function setStyleSheet() {
 
    var currentHour = new Date().getHours();
 
    if(currentHour >= 5 && currentHour < 18) {
     
        $('#time-css').attr('href', 'css/day.css');
     
    }else{
     
        $('#time-css').attr('href', 'css/night.css');
     
    }
 
}

setStyleSheet();

And then in your <head> tag you'd have the following:
Code:
<link id="time-css" rel="stylesheet" href="css/default.css" type="text/css">

So the JS would replace "css/default.css" with the current time specific CSS, otherwise if there's no JS enabled it'll stay as "css/default.css".
 

Kristopher

Photographer
Dec 25, 2010
803
68
With jQuery, this is how you'd do it:
Code:
function setStyleSheet() {

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

    if(currentHour >= 5 && currentHour < 18) {
    
        $('#time-css').attr('href', 'css/day.css');
    
    }else{
    
        $('#time-css').attr('href', 'css/night.css');
    
    }

}

setStyleSheet();

And then in your <head> tag you'd have the following:
Code:
<link id="time-css" rel="stylesheet" href="css/default.css" type="text/css">

So the JS would replace "css/default.css" with the current time specific CSS, otherwise if there's no JS enabled it'll stay as "css/default.css".
So now its just reading my default.css
It should be showing the day CSS at this current time. Any ideas?
 

Users who are viewing this thread

Top