TMS_1
TMS_1

Reputation: 21

Hide CSS class with Javascript in the afternoon each day

I am hoping to hide a css class or ID with Javascript between some hours of the day. It is for a menu, so let's say after 12pm, the menu disappears, each day and appears at maybe 8am.

I've tried searching both here and various other places but I'm unable to find a solution. Perhaps because when you search for "javascript" and "time" or "hours" it comes up with results about removing after an amount of time the item is on the page when it loads for a user. Obviously that is not what I am after here.

Here is what I am trying:

var H = new Date();
document.getElementById("hour").innerHTML = H.getHours();
var M = new Date();
document.getElementById("mins").innerHTML = M.getMinutes();

Finished JS Fiddle: http://jsfiddle.net/ft8hz5uf/6/

Upvotes: 0

Views: 419

Answers (3)

Ozan
Ozan

Reputation: 3739

You can use getHours() method of date object.

var now = new Date();
var hour = now.getHours();
if (hour > 12) {
  //12 to 23:59:59
  $("#before-noon").hide();
  $("#after-noon").show();
} else {
  //00 to 11:59:59
  $("#before-noon").show();
  $("#after-noon").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="before-noon">Before Noon</div>
<div id="after-noon">After Noon</div>

Upvotes: 0

Cristyan
Cristyan

Reputation: 670

you must do a function that takes the current time and validates if it is within the parameter you want. this should hide or show the class

 function validateTime() {
    const currentHour = new Date().getHours(); // hours from 0 to 23
    if(currentHour > 8  && currentHour < 18){ // true for the hours between 8am and 6pm
        //logic for add class
        $(query).addClass('class');
    } else {
        // logic for remove class
        $(query).removeClass('class');
    }
}

// you can make the function run every minute

setInterval(validateTime, 1000*60);

Upvotes: 1

holden
holden

Reputation: 1779

A basic approach might be:

var hours = new Date().getHours();
if (hours >= 13 && hours <= 19) {
   [do something]
} else {
    [do something else]
}

It shouldn't be necessary to remind that hours, in this case, are relative to user time (so the browser will show different thing if in Australia rather than in Europe...) If you are looking for an absolute time, regardeless the user's time, you should use a server-side approuch.

Upvotes: 2

Related Questions