Java Script add class on div between two hours and minutes - javascript

How to add class with js between eg 14.15 and 16.15?
I have something like this:
var currentTime = new Date().getHours();
if (document.body) {
if (14 <= currentTime && currentTime < 16) {
var d = document.getElementById("div1");
d.className += "active";
} else {
}
}
<div id="div1">
</div>
How can I add minutes?

What do you mean with add class?
Perhaps this is what you are looking for:
document.getElementById("MyElement").classList.add('MyClass');
document.getElementById("MyElement").classList.remove('MyClass');

You can do something like this:
var currentTime = new Date();
var currentHour = currentTime.getHours();
var currentMinute = currentTime.getMinutes();
if (
currentHour >= 14 && currentHour <= 16 &&
(
(currentHour == 14 && currentMinute >= 15) ||
(currentHour == 16 && currentMinute <= 15)
)
) {
// it is between 14:15 and 16:15
var d = document.getElementById("div1");
d.className += "active";
}

I think you should use the js Date object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
You should use classList attribute of the Element to manage the classes. https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
We can use 3 date objects ( I'm sure that shortcuts can be employed to use fewer ). We will use one as "now", one as "today at 14:15:00" and one as "today at 16:15:00". We can easily test to see if the "now" object is within the bounds of the start and end time objects:
const dateNow = new Date();
const windowStart = new Date();
const windowEnd = new Date();
// this is offset in the sandbox
windowStart.setHours(14, 15, 0);
windowEnd.setHours(16, 15, 0);
// force for debug: un comment to verify the check below
//dateNow.setHours(15,00,00);
//debugging only
console.log(`Start of window is: ${windowStart}`);
console.log(`Now time is: ${dateNow}`);
console.log(`End of window is: ${windowEnd}`);
//check to see if we are within the window of time
if (windowStart <= dateNow && dateNow <= windowEnd) {
console.log(`we are inside the window`);
var d = document.getElementById("div1");
d.classList.add("active");
} else {
console.log(`we are outside the window`);
}

Related

Based on date and time, show/hide element

I want to show and hide an element on a page based on multiple dates and times. For instance, I have an alert box that I want to show for the following dates 4/28, 4/29, and 4/30 between the hours of 9 am to 12 pm PST. And hide for the remaining hours. The posted code works for an open and closing time but I am unsure how I can add multiple dates. Or I'm just missing something.
Edit: I suck at jQuery/JavaScript.
HTML
<div class="open openstatus">Open</div>
<div class="closed openstatus">Closed</div>
JS
var now = new Date(),
currentDay = now.getDay(),
openTime = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
13,
02
),
closeTime = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
13,
03
),
open = now.getTime() > openTime.getTime() && now.getTime() < closeTime.getTime();
if (currentDay !== 6 && currentDay !== 0 && open) {
$('.openstatus').toggle();
}
I'd do something like this:
HTML
<div id="alertBox">My alert box</div>
JAVASCRIPT
function myFunc(){
var d = new Date(); //client Date
d.setMinutes(d.getMinutes() + d.getTimezoneOffset()); //To get current GMT time
d.setHours(d.getHours() - 8); // This is time in PST
var day = d.getDay(),
month = d.getMonth(),
hours = d.getHours(),
dateOfMonth = d.getDate();
var prohibbittedMonth = 4;
var prohibbittedDates =[28, 29, 30];
var showAlertBox = false;
if(day === 0 || day === 6){
showAlertBox = true; // If the day is Saturday or Sunday
}else if(month = prohibbittedMonth && prohibbittedDates.includes(dateOfMonth) && !(hours >= 0 && hours <9)){
showAlertBox = true;
}
// You may combine the above two condition in a single line. I have just separated them for better readability.
if(!showAlertBox){
document.getElementById('alertBox').style.display = "none"; //You may use your jquery here if you like
}else{
document.getElementById('alertBox').style.display = ""; //You may use your jquery here if you like
}
}
myFunc();
Cant't you add sth like this
currentDate=now.getDate();
if (currentDay !== 6 && currentDay !== 0 && open && (currentDate==28||currentDate==29||currentDate==30))
This checks if the currentDate is either 28 or 29 or 30.

show/hide div during business hours, mix with UTC?

UPDATE
I have added a current working fiddle, I feel like it should be correct, but it doesn't seem to work.
https://jsfiddle.net/bill9000/yadk6sja/2/
original question:
what I have is some code to show/hide div (basically show div during certain business hours) - is there an easy way to make this use a calculate from UTC... so that the show/hide time is fixed on a certain timezone. eg. 6pm EST instead of 6pm users time... here's my current code:
var d = new Date();
var dayOfWeek = d.getDay();
var hour = d.getHours();
var mins = d.getMinutes();
var status = 'open';
if (dayOfWeek !== 6 && dayOfWeek !== 0 && hour >= 03 && hour < 15){
//if (hour=='10' && mins < '30'){
// status = 'closed';
// }else{
status = 'open';
// }
}else{
status = 'closed';
if (status=='open') {
$b('.orderby').show();
}else{
$b('.orderby').hide();
}
also, I have some other JavaScript that's getting the UTC diff:
function ShowTime() {
var now = new Date();
var diff = now.getTimezoneOffset() / 60; //the difference between local PC and UTC
diff = diff - 4; //the difference between UTC and EST
var hrs = 18-(now.getHours()+diff); //18 is the target hour
any way of making the show/hide work for the specific time?
Date() objects are already UTC, when you use d.getDay() or d.getHours(), the local timezone is applied on the fly.
You just have to use d.getUTCDay(), d.getUTCHours(), etc. to prevent this

javascript show-hide an element in specific time

I want to know if it possible to show and hide an element at a specific time in o´clock ?
Let´s say I want the div show up everyday from 20:00 until 07:00.
Here is what I tried but I lack some lines which I have no idea for that. Please help.
function myTimer() {
var d = new Date();
document.getElementById("MyTime").innerHTML = d.toLocaleTimeString();
}
$( document ).ready(function() {
myTimer();
show_hide_me();
});
function show_hide_me () {
<------HERE START TO SHOW/ HIDE (I don´t know how to do it more)
("#MyElm")
if the time between 20:00 - 07:00 show();
else hide();
}
}
function show_hide_me () {
var myDate = new Date();
var hours = myDate.getHours();
if (hours > 20 || hours < 7){
$('#myElem').show();
} else {
$('#myElem').hide();
}
}
show_hide_me();
Demo: http://jsfiddle.net/robschmuecker/wkhWK/
var date = new Date();
var currentHours = date.getHours();
currentHours = ("0" + currentHours).slice(-2);
alert(currentHours);
if (currentHours > 20 || currentHours < 7){
$('#myElem').show();
}
else
{
$('#myElem').hide();
}
Demo:
http://jsfiddle.net/f349k/1/

How do I change a picture during the weekends with javascript?

I want to show on our site when the chat is available. The problem is that it won't be open in the weekends. How do I exclude them? Can it be done?
<html>
<body>
<script type="text/javascript">
function chatonoff(){
var now = new Date();
var hour = now.getHours();
if (hour >=9 && hour <=18)
{
document.getElementById("chat").src = "/bilder/butik/chat-open.png";
}
}
</script>
<img id="chat" src="/bilder/butik/chat.png" onload="chatonoff()">
</body>
</html>
You could do like this
function chatonoff(){
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
//Check if weekend : in this case, I assume that saturday == 6 and Sunday = 0
//It depends on your location / timezone
if(day != 6 && day != 0)
{
if (hour >=9 && hour <=18)
{
document.getElementById("chat").src = "/bilder/butik/chat-open.png";
}
}
}
EDIT
About excluding hollidays :
You should create an array with all the off dates. Then, check if the curent day is present in the array
var offDaysListArray = ['2013-01-01','2013-01-02'];
var now = new Date();
var y = now .getFullYear();
var d = (now .getDate() < 10) ? '0'+now .getDate() : now .getDate();
var m = ((now .getMonth()+1) < 10) ? '0'+(now .getMonth()+1) : (now .getMonth()+1);
//Check if it is a closed day
if(offDaysListArray.indexOf(y + '-' + m + '-' + d) != -1)
return false; //It is a close day
Be carefull with indexOf, old browser like IE8 doesn't implement this function. Check Why doesn't indexOf work on an array IE8?
This is a very simple answer, although it won't exactly work as you want it to as JavaScript is run on the client side.
This means that someone on the other side of the world will be able to see your chat on HIS FRIDAY even though it is a SATURDAY for YOU (A Sunday/Monday example also works here). Ideally you would solve this by using some server side language such as Java / .NET / PHP or whatever you are using.
Here is your quick JavaScript fix:
<html>
<body>
<script type="text/javascript">
function chatonoff(){
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
if (hour >=9 && hour <=18 && day >= 1 && day <= 5)
{
document.getElementById("chat").src = "/bilder/butik/chat-open.png";
}
}
</script>
<img id="chat" src="/bilder/butik/chat.png" onload="chatonoff()">
</body>
</html>

Compare current time between a given period in JQuery

I want to check whether the current time is between 10.30AM and 11.30AM with Jquery. How would I do this in correct manner?
I've tried the following way and its not working as I expected
function compareTime(){
var d = new Date(), // current time
hours = d.getHours(),// current hour
mins = d.getMinutes(); // current minute
var sTime = "10.30";
var eTime = "11.30";
var cTime = hours+'.'+mins;
if(sTime < cTime < eTime){
// here i want to do something if the current time is in between ...
}else{
}
}
Nothing to do with jQuery:
function checkTime(d) {
d = d || new Date();
var minTime = new Date(d);
var maxTime = new Date(d);
minTime.setHours(10, 30, 0, 0);
maxTime.setHours(11, 30, 0, 0);
return d > minTime && d < maxTime;
}
you can do like this,
var sTime = "10.30"
sTime = sTime.split(".");
var eTime = "11.30";
eTime = eTime.split(".");
so that eTime and sTime will become an array with sTime[0] = "10" and sTime[1] = "30", similarly eTime also. Now develop a loop to compare it with hours and mins.

Categories

Resources