Skip to content Skip to sidebar Skip to footer

Stop/hide Javascript Running Depending On Current Day And Time? (jquery?)

I am working on a project (live chat) which uses some javascript code to place a chat button onto a web page. What I'd like to do, depending specifically on which day of the week i

Solution 1:

Look more into Date()

// 0 Sunday// 1 Monday// 2 Tuesday// ...// 6 Saturdayvar d = newDate();
var openHours = 0;
var closedHours = 0;

switch(d.getDay()) {
    case0:
        openHours = 7;
        closeHours = 17;
        break;
    case1:
        openHours = 8;
        closeHours = 18;
        break;
    case2:
        openHours = 7;
        closeHours = 17;
        break;
    case3:
        openHours = 8;
        closeHours = 18;
    case4:
        openHours = 7;
        closeHours = 17;
        break;
    case5:
        openHours = 7;
        closeHours = 17;
        break;
    case6:
        openHours = 9;
        closeHours = 15;
        break;
}


if(d.getHours() >= openHours && d.getHours() <= closeHours) {
    $(".open").show();
    $(".closed").hide();
}else {
    $(".open").hide();
    $(".closed").show();
}

This will set the hours depending on the day and display them accordingly

Solution 2:

You can use the getDay function to return the day of the week 0-6

if(d.getDay() < 5){ //weekday hoursif(d.getHours() >= 7 && d.getHours() <= 15 ){
    $(".open").show();
    $(".closed").hide();
  }//and so on
}

Solution 3:

date and time calculation can be really confusing and once we add code we always keep adding the logic on top of the previously written code.

So it's important that we make it clear and readable.

Here is what I will do

1- create weekday array so we don't have to keep track of zero index weekday from d.getHours() and always figure out what does 0,3,5 means....

2- create readable object literal with properties for each day and assign open and close time.

var d = new Date();

var weekDays =
 ['monday', 'tuesday','wednesday','thursday','friday','saturday','sunday'];

var weeklyTimeTable = {
    monday: { open: 7, close: 10 },
    tuesday: { open: 8, close: 10 },
    wednesday: { open: 9, close: 10 },
    thursday: { open: 10, close: 10 },
    friday: { open: 7, close: 10 },
    saturday: { open: 8, close: 10 },
    sunady: { open: 9, close: 10 }

}

functionshowOpenClose() {
    $('.open').hide();
    $('.closed').hide();

    if (d.getHours() >= weeklyTimeTable[weekDays[d.getDay()-1]].open && 
        d.getHours() <= weeklyTimeTable[weekDays[d.getDay()-1]].close) {
        $('.open').show();
    } else {
        $'.closed').show();
    }
}

Post a Comment for "Stop/hide Javascript Running Depending On Current Day And Time? (jquery?)"