Search code examples
javascriptjquerycsstimefade

Fade element in/out at certain time of day


I've been looking everywhere with no luck so far.

I want to fade a div in/out at set times. Not at a set time of delay from page load. For example. I want a div to fade to black when it reaches 17:00 on the local machine/server's time (depending on how it can be done) and back in at 09:00 for example. I don't know if JS/JQuery can do this on it's own, or if PHP would need to be involved.

So far I have this for the div fade, but it's using a 6 second delay, rather than triggering at a certain time of day.

$(document).ready(function() {
setTimeout(function() {
    $("div.fade-me").fadeOut("slow", function() {
        $("div.fade-me").remove();
    });
}, 6000); // 6 seconds
});

Solution

  • Here is an example on how to do it using Date object.

    Sample HTML:

    <div>
        <div id="timeSensitive">I appear at 10:00 until 13:00 (inclusive).</div>
        <div id="otherTime">I appear before 10:00 and after 13:00 (exclusive)</div>
    </div>
    

    And here's the JavaScript to enable it showing/hiding a div depending on time of day:

    //i am only comparing hours here, you can be more granular and use minutes and seconds too.
    
    function CheckTime()
    {
        var date = new Date();
        var specialTime = date.getHours() >= 10 && date.getHours() <= 13;
        $("#timeSensitive").toggle(specialTime);
        $("#otherTime").toggle(!specialTime);
    
    }
    
    $(function(){
       CheckTime();
       var interval = setInterval(CheckTime, 1000); //check every second
    });