jquerytimeofday

Add class depending on time of day not working


Hi I found some code here and have tweaked it to add a class to depending on the time of day but its not working, i saw it working for a split second today but no class is being added atm and i don't know why.

<script type="text/javascript">
jQuery(document).ready(function(){
    var url, hour = new Date().getHours();
    if (hour > 8 && hour < 18) {
        jQuery('body').addClass('day');
    } else if (hour > 18 && hour < 21) {
        jQuery('body').addClass('midday');
    } else if (hour > 21 && hour < 8) {
        jQuery('body').addClass('night');
    }
});
</script>

You can see the code in operation here: http://www.bbdimension.co.uk/files/wp/ basically the idea is for the current region (spain time) if its between 08:00 and 18:00 it adds a class of day, else if its between 18:00 and 21:00 it adds a class of midday and else if its between 21:00 and 08:00 it adds a class of night.

Am I doing something wrong, im not a JS guru. I couldn't use the $ dollar sign because it was conflicting with other things on the site.


Solution

  • hour = new Date().getHours();
    

    then if you alert hour you will get 0 , because getHours() returns between 0-23

    and since 0 > 21 = false your last condition wont be true

    rewrite your last condition as following

    else if (hour > 21 || hour < 8) 
    

    then it will alert "night"