I'm trying to figure out how to change my website's background by season using CSS and Javascript. It seems like it should be easy but I'm just not getting anywhere on it. Here's what I was trying, which doesn't work (of course, right?):
<script>
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var total = month;
// Summer
if (total >= 6 && total <= 8)
{
var season = "summer.jpg";
}
// Autumn
else if (total >= 9 && total <= 11)
{
var season = "fall.jpg";
}
// Winter
else if (total == 12 || total == 1 || total == 2)
{
var season = "winter.jpg";
}
// Spring
else if (total >= 2 && total <= 6)
{
var season = "spring.jpg";
}
else
{
var season = "summer.jpg";
}
</script>
<style type="text/css">
#maincontent{
position: fixed;
left: 200px; /*Set left value to WidthOfLeftFrameDiv*/
top: 0px; /*Set top value to HeightOfTopFrameDiv*/
right: 0;
bottom: 0;
overflow: auto;
background-image: url('season'); /*Note: I tried putting season in <scirpt> tags too with no success */
</style>
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var total = month;
switch(total) {
case (total >= 6 && total <= 8):
var season = "summer.jpg";
break;
case (total >= 9 && total <= 11):
var season = "fall.jpg";
break;
case (total == 12 || total == 1 || total == 2):
var season = "winter.jpg";
break;
default:
var season = "summer.jpg";
}
var output = "red url('" + season + "') no-repeat center center fixed";
var content= document.getElementById('maincontent');
content.style.background = output;
Use Pure Javascript to set background images according to your conditions. For reference I've added a text that shows you the current season.
Please have a look at the code below.
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var total = month;
console.log('currentTime: ', currentTime);
console.log('month: ', month);
console.log('total: ', total);
var myElement = document.querySelector("#maincontent");
var textSelector = function(divId) {
var textElement = document.getElementById(divId);
return textElement;
}
// Summer
if (total >= 6 && total <= 8)
{
var season = "summer.jpg";
myElement.style.backgroundImage = "url('http://placehold.it/500x500')";
textSelector('seasonOne').innerHTML = 'Season (Summer)';
}
// Autumn
else if (total >= 9 && total <= 11)
{
var season = "fall.jpg";
myElement.style.backgroundImage = "url('http://placehold.it/500x500')";
textSelector('seasonTwo').innerHTML = 'Season (Fall)';
}
// Winter
else if (total == 12 || total == 1 || total == 2)
{
var season = "winter.jpg";
myElement.style.backgroundImage = "url('http://placehold.it/500x500')";
textSelector('seasonThree').innerHTML = 'Season (Winter)';
}
// Spring
else if (total >= 2 && total <= 6)
{
var season = "spring.jpg";
myElement.style.backgroundImage = "url('http://placehold.it/500x500')";
textSelector('seasonThree').innerHTML = 'Season (Spring)';
}
else
{
var season = "summer.jpg";
myElement.style.backgroundImage = "url('http://placehold.it/500x500')";
textSelector('seasonThree').innerHTML = 'Season (Summer)';
}
#maincontent {
position: fixed;
left: 200px; /*Set left value to WidthOfLeftFrameDiv*/
top: 0px; /*Set top value to HeightOfTopFrameDiv*/
right: 0;
bottom: 0;
overflow: auto;
background-image: url('season');
background: #aaa;
}
.txt {
padding: 10px 40px;
font-weight: 700;
}
<div id="maincontent">
<div id="seasonOne" class="txt"></div>
<div id="seasonTwo" class="txt"></div>
<div id="seasonThree" class="txt"></div>
<div id="seasonFour" class="txt"></div>
<div id="seasonFive" class="txt"></div>
</div>
Hope this helps!
The accepted answers switch statement doesn't actually work, this really annoyed and confused me for a while, solution is to use 'true' as the switch argument:
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
switch(true) {
case (month >= 6 && month <= 8):
var season = "summer.jpg";
break;
case (month >= 9 && month <= 11):
var season = "fall.jpg";
break;
case (month == 12 || month == 1 || month == 2):
var season = "winter.jpg";
break;
default:
var season = "summer.jpg";
}
Try this:
var main = document.getElementById('maincontent');
main.style.backgroundImage = "url(" + season + ")";
You should set the style inline...
var maincontent = document.getElementById("#maincontent");
var season = "summer";
if (condition) {
season = "fall"
}
// list all your conditions
maincontent.style.backgroundImage = "url(" + season + ".jpg)";
You can achieve this by using jquery,
after assigned value for season do like below,
$("#maincontent").css("background-image","url(" + season + ")");
By using javascript,
document.getElementById("maincontent").style.backgroundImage = "url(" + season + ")";
Related
I'm trying to add a datepicker to a page I'm creating. Since I don't know much at all about Javascript I'm modifying an example I've found at https://code-boxx.com/simple-datepicker-pure-javascript-css/. I don't want any extra pages or files as I need the form I'm creating to be entirely self-contained. I've condensed it down to this:
<!DOCTYPE html>
<html>
<head>
<title>Simple Date Picker Example</title>
<style>
/* (A) POPUP */
.picker-wrap {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0,0,0,0.5);
opacity: 0;
visibility: hidden;
transition: opacity 0.2s;
}
.picker-wrap.show {
opacity: 1;
visibility: visible;
}
.picker-wrap .picker {
margin: 50vh auto 0 auto;
transform: translateY(-50%);
}
/* (B) CONTAINER */
.picker {
max-width: 300px;
background: #444444;
padding: 10px;
}
/* (C) MONTH + YEAR */
.picker-m, .picker-y {
width: 50%;
padding: 5px;
box-sizing: border-box;
font-size: 16px;
}
/* (D) DAY */
.picker-d table {
color: #fff;
border-collapse: separate;
width: 100%;
margin-top: 10px;
}
.picker-d table td {
width: 14.28%; /* 7 EQUAL COLUMNS */
padding: 5px;
text-align: center;
}
/* HEADER CELLS */
.picker-d-h td {
font-weight: bold;
}
/* BLANK DATES */
.picker-d-b {
background: #4e4e4e;
}
/* TODAY */
.picker-d-td {
background: #d84f4f;
}
/* PICKABLE DATES */
.picker-d-d:hover {
cursor: pointer;
/* UNPICKABLE DATES */
.picker-d-dd {
color: #888;
background: #4e4e4e;
}
</style>
<!-- (A) LOAD DATE PICKER -->
<!--<link href="dp-dark.css" rel="stylesheet">-->
<link href="dp-light.css" rel="stylesheet" />
<script src="datepicker.js"></script>
</head>
<body>
<!-- (B) THE HTML -->
<!-- (B1) INLINE DATE PICKER -->
<input type="text" id="input-inline" placeholder="Inline" />
<div id="pick-inline"></div>
<!-- (B2) POPUP DATE PICKER -->
<input type="text" id="input-pop" placeholder="Popup" />
<!-- (C) ATTACH DATE PICKER ON LOAD -->
<script>
window.addEventListener("load", function () {
// (C1) INLINE DATE PICKER
picker.attach({
target: "input-inline",
container: "pick-inline",
});
// (C2) POPUP DATE PICKER
picker.attach({
target: "input-pop",
});
});
</script>
</body>
<script>
var picker = {
// (A) ATTACH DATEPICKER TO TARGET
// target : datepicker will populate this field
// container : datepicker will be generated in this container
// startmon : start on Monday (default false)
// disableday : array of days to disable, e.g. [2,7] to disable Tue and Sun
attach: function (opt) {
// (A1) CREATE NEW DATEPICKER
var dp = document.createElement("div");
dp.dataset.target = opt.target;
dp.dataset.startmon = opt.startmon ? "1" : "0";
dp.classList.add("picker");
if (opt.disableday) {
dp.dataset.disableday = JSON.stringify(opt.disableday);
}
// (A2) DEFAULT TO CURRENT MONTH + YEAR - NOTE: UTC+0!
var today = new Date(),
thisMonth = today.getUTCMonth(), // Note: Jan is 0
thisYear = today.getUTCFullYear(),
months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
// (A3) MONTH SELECT
var select = document.createElement("select"),
option = null;
select.classList.add("picker-m");
for (var mth in months) {
option = document.createElement("option");
option.value = parseInt(mth) + 1;
option.text = months[mth];
select.appendChild(option);
}
select.selectedIndex = thisMonth;
select.addEventListener("change", function () {
picker.draw(this);
});
dp.appendChild(select);
// (A4) YEAR SELECT
var yRange = 10; // Year range to show, I.E. from thisYear-yRange to thisYear+yRange
select = document.createElement("select");
select.classList.add("picker-y");
for (var y = thisYear - yRange; y < thisYear + yRange; y++) {
option = document.createElement("option");
option.value = y;
option.text = y;
select.appendChild(option);
}
select.selectedIndex = yRange;
select.addEventListener("change", function () {
picker.draw(this);
});
dp.appendChild(select);
// (A5) DAY SELECT
var days = document.createElement("div");
days.classList.add("picker-d");
dp.appendChild(days);
// (A6) ATTACH DATE PICKER TO TARGET CONTAINER + DRAW THE DATES
picker.draw(select);
// (A6-I) INLINE DATE PICKER
if (opt.container) {
document.getElementById(opt.container).appendChild(dp);
}
// (A6-P) POPUP DATE PICKER
else {
// (A6-P-1) MARK THIS AS A "POPUP"
var uniqueID = 0;
while (document.getElementById("picker-" + uniqueID) != null) {
uniqueID = Math.floor(Math.random() * (100 - 2)) + 1;
}
dp.dataset.popup = "1";
dp.dataset.dpid = uniqueID;
// (A6-P-2) CREATE WRAPPER
var wrapper = document.createElement("div");
wrapper.id = "picker-" + uniqueID;
wrapper.classList.add("picker-wrap");
wrapper.appendChild(dp);
// (A6-P-3) ATTACH ONCLICK TO SHOW/HIDE DATEPICKER
var target = document.getElementById(opt.target);
target.dataset.dp = uniqueID;
target.readOnly = true; // Prevent onscreen keyboar on mobile devices
target.onfocus = function () {
document
.getElementById("picker-" + this.dataset.dp)
.classList.add("show");
};
wrapper.addEventListener("click", function (evt) {
if (evt.target.classList.contains("picker-wrap")) {
this.classList.remove("show");
}
});
// (A6-P-4) ATTACH POPUP DATEPICKER TO BODY
document.body.appendChild(wrapper);
}
},
// (B) DRAW THE DAYS IN MONTH
// el : HTML reference to either year or month selector
draw: function (el) {
// (B1) GET DATE PICKER COMPONENTS
var parent = el.parentElement,
year = parent.getElementsByClassName("picker-y")[0].value,
month = parent.getElementsByClassName("picker-m")[0].value,
days = parent.getElementsByClassName("picker-d")[0];
// (B2) DATE RANGE CALCULATION - NOTE: UTC+0!
var daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate(),
startDay = new Date(Date.UTC(year, month - 1, 1)).getUTCDay(), // Note: Sun = 0
endDay = new Date(Date.UTC(year, month - 1, daysInMonth)).getUTCDay(),
startDay = startDay == 0 ? 7 : startDay,
endDay = endDay == 0 ? 7 : endDay;
// (B3) GENERATE DATE SQUARES (IN ARRAY FIRST)
var squares = [],
disableday = null;
if (parent.dataset.disableday) {
disableday = JSON.parse(parent.dataset.disableday);
}
// (B4) EMPTY SQUARES BEFORE FIRST DAY OF MONTH
if (parent.dataset.startmon == "1" && startDay != 1) {
for (var i = 1; i < startDay; i++) {
squares.push("B");
}
}
if (parent.dataset.startmon == "0" && startDay != 7) {
for (var i = 0; i < startDay; i++) {
squares.push("B");
}
}
// (B5) DAYS OF MONTH
// (B5-1) ALL DAYS ENABLED, JUST ADD
if (disableday == null) {
for (var i = 1; i <= daysInMonth; i++) {
squares.push([i, false]);
}
}
// (B5-2) SOME DAYS DISABLED
else {
var thisday = startDay;
for (var i = 1; i <= daysInMonth; i++) {
// CHECK IF DAY IS DISABLED
var disabled = disableday.includes(thisday);
// DAY OF MONTH, DISABLED
squares.push([i, disabled]);
// NEXT DAY
thisday++;
if (thisday == 8) {
thisday = 1;
}
}
}
// (B6) EMPTY SQUARES AFTER LAST DAY OF MONTH
if (parent.dataset.startmon == "1" && endDay != 7) {
for (var i = endDay; i < 7; i++) {
squares.push("B");
}
}
if (parent.dataset.startmon == "0" && endDay != 6) {
for (var i = endDay; i < (endDay == 7 ? 13 : 6); i++) {
squares.push("B");
}
}
// (B7) DRAW HTML
var daynames = ["Mon", "Tue", "Wed", "Thur", "Fri", "Sat"];
if (parent.dataset.startmon == "1") {
daynames.push("Sun");
} else {
daynames.unshift("Sun");
}
// (B7-1) HTML DATE HEADER
var table = document.createElement("table"),
row = table.insertRow(),
cell = null;
row.classList.add("picker-d-h");
for (let d of daynames) {
cell = row.insertCell();
cell.innerHTML = d;
}
// (B7-2) HTML DATE CELLS
var total = squares.length,
row = table.insertRow(),
today = new Date(),
todayDate = null;
if (
today.getUTCMonth() + 1 == month &&
today.getUTCFullYear() == year
) {
todayDate = today.getUTCDate();
}
for (var i = 0; i < total; i++) {
if (i != total && i % 7 == 0) {
row = table.insertRow();
}
cell = row.insertCell();
if (squares[i] == "B") {
cell.classList.add("picker-d-b");
} else {
cell.innerHTML = squares[i][0];
// NOT ALLOWED TO CHOOSE THIS DAY
if (squares[i][1]) {
cell.classList.add("picker-d-dd");
}
// ALLOWED TO CHOOSE THIS DAY
else {
if (i == todayDate) {
cell.classList.add("picker-d-td");
}
cell.classList.add("picker-d-d");
cell.addEventListener("click", function () {
picker.pick(this);
});
}
}
}
// (B7-3) ATTACH NEW CALENDAR TO DATEPICKER
days.innerHTML = "";
days.appendChild(table);
},
// (C) CHOOSE A DATE
// el : HTML reference to selected date cell
pick: function (el) {
// (C1) GET ALL COMPONENTS
var parent = el.parentElement;
while (!parent.classList.contains("picker")) {
parent = parent.parentElement;
}
// (C2) GET FULL SELECTED YEAR MONTH DAY
var year = parent.getElementsByClassName("picker-y")[0].value,
month = parent.getElementsByClassName("picker-m")[0].value,
day = el.innerHTML;
// YYYY-MM-DD FORMAT - CHANGE FORMAT HERE IF YOU WANT !
if (parseInt(month) < 10) {
month = "0" + month;
}
if (parseInt(day) < 10) {
day = "0" + day;
}
var fullDate = year + "-" + month + "-" + day;
// (C3) UPDATE SELECTED DATE
document.getElementById(parent.dataset.target).value = fullDate;
// (C4) POPUP ONLY - CLOSE THE POPUP
if (parent.dataset.popup == "1") {
document
.getElementById("picker-" + parent.dataset.dpid)
.classList.remove("show");
}
},
};
</script>
</html>
Since I don't want the inline date picker and only want the pop-up date picker, I thought all I would need to do is remove this section:
<!-- (B1) INLINE DATE PICKER -->
<input type="text" id="input-inline" placeholder="Inline"/>
<div id="pick-inline"></div>
but when I do that the pop-up stops working as well. What do I need to change to remove the inline but just keep the pop-up?
You commented the template code for the inline date picker, but you have not commented the script for inline date picker.
Comment out the below code to make your solution working.
// Comment this code block in script
picker.attach({
target: "input-inline",
container: "pick-inline",
});
Why this was throwing error?
The datepicker was trying to find a target from dom having id input-inline. Since you have commented it out, it will not be available. Thats why it was stoping the execution of javascript. The code got broken there and the lines below that is not executed. This is why your popup date picker was also not working.
Working Fiddle
window.addEventListener("load", function () {
// (C1) INLINE DATE PICKER
// picker.attach({
// target: "input-inline",
// container: "pick-inline",
// });
// (C2) POPUP DATE PICKER
picker.attach({
target: "input-pop",
});
});
var picker = {
// (A) ATTACH DATEPICKER TO TARGET
// target : datepicker will populate this field
// container : datepicker will be generated in this container
// startmon : start on Monday (default false)
// disableday : array of days to disable, e.g. [2,7] to disable Tue and Sun
attach: function (opt) {
// (A1) CREATE NEW DATEPICKER
var dp = document.createElement("div");
dp.dataset.target = opt.target;
dp.dataset.startmon = opt.startmon ? "1" : "0";
dp.classList.add("picker");
if (opt.disableday) {
dp.dataset.disableday = JSON.stringify(opt.disableday);
}
// (A2) DEFAULT TO CURRENT MONTH + YEAR - NOTE: UTC+0!
var today = new Date(),
thisMonth = today.getUTCMonth(), // Note: Jan is 0
thisYear = today.getUTCFullYear(),
months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
// (A3) MONTH SELECT
var select = document.createElement("select"),
option = null;
select.classList.add("picker-m");
for (var mth in months) {
option = document.createElement("option");
option.value = parseInt(mth) + 1;
option.text = months[mth];
select.appendChild(option);
}
select.selectedIndex = thisMonth;
select.addEventListener("change", function () {
picker.draw(this);
});
dp.appendChild(select);
// (A4) YEAR SELECT
var yRange = 10; // Year range to show, I.E. from thisYear-yRange to thisYear+yRange
select = document.createElement("select");
select.classList.add("picker-y");
for (var y = thisYear - yRange; y < thisYear + yRange; y++) {
option = document.createElement("option");
option.value = y;
option.text = y;
select.appendChild(option);
}
select.selectedIndex = yRange;
select.addEventListener("change", function () {
picker.draw(this);
});
dp.appendChild(select);
// (A5) DAY SELECT
var days = document.createElement("div");
days.classList.add("picker-d");
dp.appendChild(days);
// (A6) ATTACH DATE PICKER TO TARGET CONTAINER + DRAW THE DATES
picker.draw(select);
// (A6-I) INLINE DATE PICKER
if (opt.container) {
document.getElementById(opt.container).appendChild(dp);
}
// (A6-P) POPUP DATE PICKER
else {
// (A6-P-1) MARK THIS AS A "POPUP"
var uniqueID = 0;
while (document.getElementById("picker-" + uniqueID) != null) {
uniqueID = Math.floor(Math.random() * (100 - 2)) + 1;
}
dp.dataset.popup = "1";
dp.dataset.dpid = uniqueID;
// (A6-P-2) CREATE WRAPPER
var wrapper = document.createElement("div");
wrapper.id = "picker-" + uniqueID;
wrapper.classList.add("picker-wrap");
wrapper.appendChild(dp);
// (A6-P-3) ATTACH ONCLICK TO SHOW/HIDE DATEPICKER
var target = document.getElementById(opt.target);
target.dataset.dp = uniqueID;
target.readOnly = true; // Prevent onscreen keyboar on mobile devices
target.onfocus = function () {
document
.getElementById("picker-" + this.dataset.dp)
.classList.add("show");
};
wrapper.addEventListener("click", function (evt) {
if (evt.target.classList.contains("picker-wrap")) {
this.classList.remove("show");
}
});
// (A6-P-4) ATTACH POPUP DATEPICKER TO BODY
document.body.appendChild(wrapper);
}
},
// (B) DRAW THE DAYS IN MONTH
// el : HTML reference to either year or month selector
draw: function (el) {
// (B1) GET DATE PICKER COMPONENTS
var parent = el.parentElement,
year = parent.getElementsByClassName("picker-y")[0].value,
month = parent.getElementsByClassName("picker-m")[0].value,
days = parent.getElementsByClassName("picker-d")[0];
// (B2) DATE RANGE CALCULATION - NOTE: UTC+0!
var daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate(),
startDay = new Date(Date.UTC(year, month - 1, 1)).getUTCDay(), // Note: Sun = 0
endDay = new Date(Date.UTC(year, month - 1, daysInMonth)).getUTCDay(),
startDay = startDay == 0 ? 7 : startDay,
endDay = endDay == 0 ? 7 : endDay;
// (B3) GENERATE DATE SQUARES (IN ARRAY FIRST)
var squares = [],
disableday = null;
if (parent.dataset.disableday) {
disableday = JSON.parse(parent.dataset.disableday);
}
// (B4) EMPTY SQUARES BEFORE FIRST DAY OF MONTH
if (parent.dataset.startmon == "1" && startDay != 1) {
for (var i = 1; i < startDay; i++) {
squares.push("B");
}
}
if (parent.dataset.startmon == "0" && startDay != 7) {
for (var i = 0; i < startDay; i++) {
squares.push("B");
}
}
// (B5) DAYS OF MONTH
// (B5-1) ALL DAYS ENABLED, JUST ADD
if (disableday == null) {
for (var i = 1; i <= daysInMonth; i++) {
squares.push([i, false]);
}
}
// (B5-2) SOME DAYS DISABLED
else {
var thisday = startDay;
for (var i = 1; i <= daysInMonth; i++) {
// CHECK IF DAY IS DISABLED
var disabled = disableday.includes(thisday);
// DAY OF MONTH, DISABLED
squares.push([i, disabled]);
// NEXT DAY
thisday++;
if (thisday == 8) {
thisday = 1;
}
}
}
// (B6) EMPTY SQUARES AFTER LAST DAY OF MONTH
if (parent.dataset.startmon == "1" && endDay != 7) {
for (var i = endDay; i < 7; i++) {
squares.push("B");
}
}
if (parent.dataset.startmon == "0" && endDay != 6) {
for (var i = endDay; i < (endDay == 7 ? 13 : 6); i++) {
squares.push("B");
}
}
// (B7) DRAW HTML
var daynames = ["Mon", "Tue", "Wed", "Thur", "Fri", "Sat"];
if (parent.dataset.startmon == "1") {
daynames.push("Sun");
} else {
daynames.unshift("Sun");
}
// (B7-1) HTML DATE HEADER
var table = document.createElement("table"),
row = table.insertRow(),
cell = null;
row.classList.add("picker-d-h");
for (let d of daynames) {
cell = row.insertCell();
cell.innerHTML = d;
}
// (B7-2) HTML DATE CELLS
var total = squares.length,
row = table.insertRow(),
today = new Date(),
todayDate = null;
if (
today.getUTCMonth() + 1 == month &&
today.getUTCFullYear() == year
) {
todayDate = today.getUTCDate();
}
for (var i = 0; i < total; i++) {
if (i != total && i % 7 == 0) {
row = table.insertRow();
}
cell = row.insertCell();
if (squares[i] == "B") {
cell.classList.add("picker-d-b");
} else {
cell.innerHTML = squares[i][0];
// NOT ALLOWED TO CHOOSE THIS DAY
if (squares[i][1]) {
cell.classList.add("picker-d-dd");
}
// ALLOWED TO CHOOSE THIS DAY
else {
if (i == todayDate) {
cell.classList.add("picker-d-td");
}
cell.classList.add("picker-d-d");
cell.addEventListener("click", function () {
picker.pick(this);
});
}
}
}
// (B7-3) ATTACH NEW CALENDAR TO DATEPICKER
days.innerHTML = "";
days.appendChild(table);
},
// (C) CHOOSE A DATE
// el : HTML reference to selected date cell
pick: function (el) {
// (C1) GET ALL COMPONENTS
var parent = el.parentElement;
while (!parent.classList.contains("picker")) {
parent = parent.parentElement;
}
// (C2) GET FULL SELECTED YEAR MONTH DAY
var year = parent.getElementsByClassName("picker-y")[0].value,
month = parent.getElementsByClassName("picker-m")[0].value,
day = el.innerHTML;
// YYYY-MM-DD FORMAT - CHANGE FORMAT HERE IF YOU WANT !
if (parseInt(month) < 10) {
month = "0" + month;
}
if (parseInt(day) < 10) {
day = "0" + day;
}
var fullDate = year + "-" + month + "-" + day;
// (C3) UPDATE SELECTED DATE
document.getElementById(parent.dataset.target).value = fullDate;
// (C4) POPUP ONLY - CLOSE THE POPUP
if (parent.dataset.popup == "1") {
document
.getElementById("picker-" + parent.dataset.dpid)
.classList.remove("show");
}
},
};
/* (A) POPUP */
.picker-wrap {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.5);
opacity: 0;
visibility: hidden;
transition: opacity 0.2s;
}
.picker-wrap.show {
opacity: 1;
visibility: visible;
}
.picker-wrap .picker {
margin: 50vh auto 0 auto;
transform: translateY(-50%);
}
/* (B) CONTAINER */
.picker {
max-width: 300px;
background: #444444;
padding: 10px;
}
/* (C) MONTH + YEAR */
.picker-m,
.picker-y {
width: 50%;
padding: 5px;
box-sizing: border-box;
font-size: 16px;
}
/* (D) DAY */
.picker-d table {
color: #fff;
border-collapse: separate;
width: 100%;
margin-top: 10px;
}
.picker-d table td {
width: 14.28%;
/* 7 EQUAL COLUMNS */
padding: 5px;
text-align: center;
}
/* HEADER CELLS */
.picker-d-h td {
font-weight: bold;
}
/* BLANK DATES */
.picker-d-b {
background: #4e4e4e;
}
/* TODAY */
.picker-d-td {
background: #d84f4f;
}
/* PICKABLE DATES */
.picker-d-d:hover {
cursor: pointer;
/* UNPICKABLE DATES */
.picker-d-dd {
color: #888;
background: #4e4e4e;
}
}
<!-- (B) THE HTML -->
<!-- (B1) INLINE DATE PICKER -->
<!-- <input type="text" id="input-inline" placeholder="Inline" />
<div id="pick-inline"></div> -->
<!-- (B2) POPUP DATE PICKER -->
<input type="text" id="input-pop" placeholder="Popup" />
I'm trying to display Open or Closed based on a shift (two Shifts daily) using Javascript. I want to be able to use that data which is stored within a span and then determine if the business is open or closed and display that. for me only one shift is working during second shift its displaying We are now closed.
Might be something better to do the same but only in HTML.
any other suggestion is appreciated.
Here is the code I have so far:
function isOpen(timeRangeEl, date) {
var day = '' + date.getDay();
var hhmm = ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
var days = timeRangeEl.getAttribute('data-days');
var openTime = timeRangeEl.getAttribute('data-open');
var closeTime = timeRangeEl.getAttribute('data-close');
return days.indexOf(day) >= 0 && openTime <= hhmm && hhmm < closeTime;
}
function openClose() {
var date = new Date();
var display = document.getElementById('open-display');
var els = display.getElementsByClassName('timerange');
var anyActive = false;
for (var i = 0; i < els.length; i++) {
if (isOpen(els[i], date)) {
anyActive = true;
els[i].className = els[i].className.replace(/ *inactive\b/g, '');
} else if (els[i].className.indexOf('inactive') < 0) {
els[i].className += ' inactive';
}
}
if (anyActive) {
display.className = 'open';
} else {
display.className = 'closed';
}
}
setInterval(openClose, 5000);
openClose();
#open-display.open > .timerange.inactive,
#open-display.open > .timerange2.inactive,
#open-display.open .days {
display: none;
}
#open-display.open > .openclosed::before {
content: 'We are now Open';
}
#open-display.closed > .openclosed::before {
content: 'We are now Closed';
}
<div class="text">
<h3>Working Hours</h3>
<div id="open-display">
<div class="openclosed"></div>
<div class="timerange" data-days="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31" data-open="12:30" data-close="15:30"><span class="days">Noon</span> 12:30pm - 3:30pm</div>
<div class="timerange2" data-days="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31" data-open="18:00" data-close="00:30"><span class="days">Dine</span> 6:00pm - 12:30am</div>
</div>
</div>
Successfully done after trying and doing trial and error method.
var doc = document;
clock({
twentyfour: !!twentyfour,
padzero: true,
refresh: 5000,
success: function(clock) {
doc.getElementById('time').innerHTML = clock.hour() + ":" + clock.minute();
document.getElementById('todate').innerHTML = clock.date() + ' ' + translate[current].month[clock.month()] + ' ' + clock.year();
document.getElementById('today').innerHTML = translate[current].weekday[clock.day()]
}
});
function mainUpdate(type) {
doc.getElementById("sunrise").innerHTML = weather.sunriseTimeFormatted;
doc.getElementById("sunset").innerHTML = weather.sunsetTimeFormatted;
var dtime = document.getElementById('time');
var dsunrise = document.getElementById('sunrise');
var dsunset = document.getElementById('sunset');
var sunriseI = document.getElementById('sunriseImg');
var sunsetI = document.getElementById('sunsetImg');
function sunriseI() {
if (dtime >= dsunrise) {
sunriseI.src = 'images/daytwilight.png';
} else {
sunriseI.src = 'images/blank.png';
}
}
function sunsetI() {
if (dtime == dsunset) {
sunsetI.src = 'images/nighttwilight.png';
} else {
sunriseI.src = 'images/blank.png';
}
}
}
<img onload="sunriseI()" id="sunriseImg" src="images/blank.png" />
<img onload="sunsetI()" id="sunsetImg" src="images/blank.png" />
not working. I wanna put twilight image on sunrise and sunset time for a while. on current time = sunset or sunrise. Or You can show me different alterrnative.Thank you for your help.
var sunrise = 5;
var sunset = 19;
var sunriseImage = "https://img.freepik.com/free-vector/mountain-landscape-background_1284-10559.jpg?size=338&ext=jpg";
var sunsetImage = "https://img.freepik.com/free-photo/3d-hazy-mountain-range-against-sunset-sky_1048-10361.jpg?size=626&ext=jpg";
var nightImage = "https://img.freepik.com/free-vector/starry-night-sky-background_23-2148058243.jpg?size=338&ext=jpg";
var dayImage = "https://img.freepik.com/free-photo/sky-with-sun-rays_1048-4473.jpg?size=626&ext=jpg";
var initClock = function(){
setInterval(function(){
var date = new Date();
var hour = date.getHours();
var minute = date.getMinutes();
var seconds = date.getSeconds();
changeTime(hour + " : " + minute + " : " + seconds);
if(hour == sunrise){
changeImage(sunriseImage);
}else if(hour == sunsetImage){
changeImage(sunsetImage);
}else if(hour > sunset || hour < sunrise){
changeImage(nightImage);
}else{
changeImage(dayImage);
}
}, 1000);
}
var changeTime = function(time){
document.getElementById("clock").innerHTML = time;
}
var changeImage = function(img){
document.getElementById("clock").style.backgroundImage = "url('"+img+"')";
document.getElementById("clock").style.backgroundSize = "cover";
}
initClock();
#clock{
width: 300px;
height: 140px;
background-size: cover;
text-align: center;
vertical-align: middle;
display: table-cell;
overflow:hidden;
background-repeat: no-repeat;
border: 1px solid black;
color: blue;
}
<div id="clock">
</div>
You should check if current time is around sunset / sunrise with some offset, and set image element's source based on that.
To compare times, First you should convert time string to a Date object. here is a function for it :
function parse_time(str){
var d_ = new Date();
d_.setHours(str.split(':')[0]);
d_.setMinutes(str.split(':')[1]);
d_.setSeconds(0);
return d_;
}
second for checking if a time is around other time with some period, you can use an isAround function like this:
function addHours(date, h) {
var result = new Date(date);
result.setTime(result.getTime() + (h*60*60*1000));
return result;
}
function isAround(d1,d2,period){
return (d1 >= (addHours(d2,-period)) && d1 <= (addHours(d2,period)));
}
And last, for checking if current time is around sunset or sunrise, use isAround function. And then set source of image element to corresponding image.
if (isAround(dtime, dsunrise, 1)) {
weatherImage.src = "sunrise_img";
}
else if (isAround(dtime, dsunset, 1)) {
weatherImage.src = 'sunset_img';
} else {
weatherImage.src = 'empty_img';
}
And also there was couple of other issues to your file, like using functions with same names as variables (sunriseI, sunsetI), using wrong variables(sunriseI in last line), using onload events which had wrong scopes and wasn't necessary, using two image elements which was unnecessary, etc.
Here is corrected code with weather check (i tested it and its working):
https://pastebin.com/dKmy8Rcu
Note that: replace clock1.0.3.2.js with your clock.js version. also i removed translate function usages in your code. also i removed weather, and replaced it with custom variables for sunset and sunrise.
I removed them because you didn't provided those in your source code, so just change them back if you have that resources.
I have been developing a site that will provide schedules created by people. I'm using Alienware to develop it and the ajax code works perfectly on the laptop all of the time. I am using IE. However, if I access my site on my Samsung Smart TV or my HTC U11 phone, Ajax isn't consistent. It displays the data I am requesting, however, when I sum up a total of hours for the week, it sometimes displays the correct hours, or sometimes shows 0 hours, when the user is scheduled for the week. Why is it inconsistent between devices? I know that Ajax is recommended for IE. As I said, though, it sometimes will display the correct total weekly hours, and other times it will just show zero. This issue isn't occurring on my Alienware.
I've already tried using onload instead of onreadystatechange. I've set the request to asynchronous and synchronous. Whether it's set to true or false, on my other devices, it fails to be consistent. I've tried it as a post and get method, and both also are inconsistent. What is wrong with my code?
function getThisWeek(str5) {
lastDate = new Date(str5);
// getting dates for this week to be displayed...
this.math = dayInput.length - 1;
this.math0 = 0 - new Date(str5).getDay();
// getting week total hour length, to determine how many times this code executes...
weekSum = 0;
totals = [];
for (this.i = 0; this.i < weekTotalHours.length; this.i++) {
str3 = this.i;
this.date = new Date(str5);
for (this.ii = (this.i * (7)) - new Date().getDay(); this.ii < (7 * (this.i + 1)) - new Date().getDay(); this.ii++) {
totalHours = 0;
this.date = new Date(str5);
this.date = new Date(this.date.setDate(this.date.getDate() + (this.ii)));
// which element position the total daily hours belongs to when displaying them...
this.pos = this.ii + new Date().getDay();
thisDayChart[this.pos].innerHTML = "";
// displaying the date
dayInput[this.pos].innerHTML = this.date.getDate();
// highlighting today's date...
if (this.date.getDate() == new Date(str5).getDate() && this.date.getMonth() == new Date().getMonth()) {
dayInput[this.pos].style.color = "white";
dayInput[this.pos].style.backgroundColor = "silver";
dayInput[this.pos].style.borderRadius = "0px";
thisDay[this.pos].style.border = "2px double lightblue";
} else {
dayInput[this.pos].style.color = "";
dayInput[this.pos].style.backgroundColor = "";
dayInput[this.pos].style.borderRadius = "";
thisDay[this.pos].style.border = "";
}
// getting schedule from database...
this.xmlhttp = new XMLHttpRequest();
this.xmlhttp.pos = this.pos;
this.xmlhttp.ipos = this.i;
this.xmlhttp.d = months[this.date.getMonth()] + " " + this.date.getDate() + ", " + this.date.getFullYear();
this.xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//alert(this.responseText);
dayInput[this.pos].m = months[new Date(this.d).getMonth()];
dayInput[this.pos].weekDay = days[new Date(this.d).getDay()];
// how many weeks in the year is user...
this.islpyr = new Date(this.d);
this.islpyr = this.islpyr.setMonth(1);
this.islpyr = new Date(new Date(this.islpyr).setDate(29));
if (this.islpyr.getMonth() == 2) {
mlens[1] = 28;
} else {
mlens[1] = 29;
}
// getting total amount of days for the year...
this.yrlen = 0;
for (this.iii = 0; this.iii < mlens.length; this.iii++) {
this.yrlen += mlens[this.iii];
}
// getting total weeks
this.wklen = this.yrlen / 7;
this.wklen = Math.round(this.wklen);
this.week = 0;
for (this.iii = 0; this.iii < new Date(this.d).getMonth(); this.iii++) {
this.week += mlens[this.iii];
}
this.week += new Date(this.d).getDate();
this.week /= 7;
this.week = Math.round(this.week) + 1;
// rounding and displaying current week number...
if (new Date(this.d).getDay() == 0) {
myDayWrapper[this.ipos].weekLabel = "Week " + this.week + " of " + this.wklen;
}
if (this.pos == 0) {
weekDisplay[0].innerHTML = myDayWrapper[0].weekLabel;
}
// which day of the year it is... how many days in the year is the user...
this.yrpos = 0;
for (this.iv = 0; this.iv < new Date(this.d).getMonth(); this.iv++) {
this.yrpos += mlens[this.iv];
}
this.yrpos += new Date(this.d).getDate();
thisDayTitle[this.pos].innerHTML = "Day " + this.yrpos + " of " + this.yrlen;
totalHours = 0;
this.schedule = "" + this.responseText;
// if user is unscheduled, do this first... 'undefined' literally means there isn't a schedule for that specific day.
if (this.schedule.search("Undefined") >= 0) {
this.elem = document.createElement("div");
this.elem.setAttribute("class","not_scheduled");
this.elem.innerHTML = "Unscheduled";
thisDayChart[this.pos].appendChild(this.elem);
this.elem = document.createElement("div");
this.elem.setAttribute("class","pick_up_shift_btn");
this.elem.innerHTML = "Claim Shifts";
this.elem.i = this.pos;
this.elem.ipos = this.ipos;
this.elem.onclick = function() {
popUpWrap[1].style.display = "block";
this.datesd = [];
for (this.i = this.ipos * 7; this.i < 7 * (this.ipos + 1); this.i++) {
this.datesd.push(dayInput[this.i].innerHTML);
}
for (this.i = 0; this.i < 7; this.i++) {
shiftClaimDate[this.i].innerHTML = this.datesd[this.i];
popUpShiftDay[this.i].innerHTML = dayInput[this.i].weekDay;
this.strrr = "" + dayInput[this.i].m;
this.strrr = this.strrr.substring(0,3);
shiftClaimMonth[this.i].innerHTML = this.strrr;
}
}
thisDayChart[this.pos].appendChild(this.elem);
if (totals.length - 1 == this.pos) {
} else {
totals.push(0);
}
} else {
// getting daily total...
this.schedule = this.schedule.split(",");
for (this.iii = 0; this.iii < this.schedule.length; this.iii++) {
this.str = "" + this.schedule[this.iii];
this.str = this.str.split("=");
this.dateString = "December 22, 1991";
switch (this.str[0]) {
case "shift_start":
this.start = new Date(this.dateString + " " + this.str[1]);
this.end = this.schedule[this.schedule.length - 1] + "";
this.end = this.end.split("=");
this.end = new Date(this.dateString + " " + this.end[1]);
this.hours = (this.end.getHours() - this.start.getHours()) * 60;
this.hours = this.hours - (this.start.getMinutes() + this.end.getMinutes());
this.hours /= 60;
totalHours += this.hours;
weekSum += totalHours;
break;
case "break_start":
this.start = new Date(this.dateString + " " + this.str[1]);
this.end = this.schedule[this.iii + 1] + "";
this.end = this.end.split("=");
this.end = new Date(this.dateString + " " + this.end[1]);
this.hours = (this.end.getHours() - this.start.getHours()) * 60;
this.hours = this.hours - (this.start.getMinutes() + this.end.getMinutes());
this.hours /= 60;
weekSum -= this.hours;
totalHours -= this.hours;
this.s = "s";
if (totalHours == 1) {
this.s = "";
}
thisDayChart[this.pos].innerHTML = totalHours + " hour" + this.s;
break;
}
}
}
weekTotalHours[this.ipos].innerHTML = "Week Total: " + weekSum;
//alert(weekSum);
// displaying hour totals...
if (new Date(this.d).getDay() == 6) {
weekSum = 0;
}
totalHours = 0;
}
}
this.xmlhttp.open("GET","/js/data/schedule.html?date="+ months[this.date.getMonth()] + " " + this.date.getDate() + ", " + this.date.getFullYear(),false);
this.xmlhttp.send();
}
}
}
I expect every device to be consistent with the hour total it should be displaying, on every device that Ajax should work on.
I'm currently working on a custom jquery/javascript countdown timer to indicate how much time a customer has left to buy something before it gets shipped. It's very crude - but it works for me, i'm not a coder per se - in basic.
jQuery(function($) {
$(document).ready(function() {
setInterval(function() {
var now = new Date();
var day = now.getDay();
//var day = 6;
var day2 = (now.getDate() < 10 ? '0' : '') + now.getDate();
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var offday = day2 + month;
var offdayset = false;
var end;
if (day >= 1 && day <= 4) {
end = new Date(now.getYear(), now.getMonth(), day, 15, 30, 0, 0);
} else if (day == 5) {
end = new Date(now.getYear(), now.getMonth(), day, 15, 30, 0, 0);
} else {
end = new Date(now.getYear(), now.getMonth(), day, 15, 30, 0, 0);
}
var timeleft = end.getTime() - now.getTime();
var diff = new Date(timeleft);
var weekday = new Array(7);
weekday[0] = "Zondag";
weekday[1] = "Maandag";
weekday[2] = "Dinsdag";
weekday[3] = "Woensdag";
weekday[4] = "Donderdag";
weekday[5] = "Vrijdag";
weekday[6] = "Zaterdag";
var shippingday = weekday[now.getDay()];
/* Declare an array. */
var offdays = new Array('2303', '2412', '2512', '3112');
/* Traverse each of value of an array using for loop to
check whether the value is exist in array*/
for (var i = 0; i < offdays.length; i++) {
if (offdays[i] === offday) {
//alert('Value exist');
offdayset = true;
}
}
if (shippingday == "Zaterdag" || shippingday == "Zondag")
{
shippingday = "Maandag";
} else if ("" + diff.getHours() + ('0' + diff.getMinutes()).slice(-2) <= 1630 && offdayset == false) {
shippingday = "Vandaag";
} else {
shippingday = weekday[now.getDay() + 1];
}
$("#datecountdown").html("binnen " + diff.getHours() + "u " + diff.getMinutes() + "min " + diff.getSeconds() + "sec");
$("#dateshipping").html(shippingday);
//below are just for testing purposes
$("#time1").html(offday);
$("#time2").html(offdayset);
$("#time3").html(end);
}, 1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="/verzending-bezorging/" class="shippingtimer" title="*wanneer product op voorraad is">
<p class="shippingtimer"> Besteld <span id="datecountdown"></span> = <span id="dateshipping"></span> verzonden*</p>
</a>
<span id="time1"></span>
<br>
<span id="time2"></span>
<br>
<span id="time3"></span>
So far i got the countdown working and the check if it's weekendl; When it's weekend (saturday or sunday) shipping will only be on Monday. However, i can't get the timer to indicate this into a bigger set of hours: i.e After 16.30 on friday Friday will be +72h, Saturday would be + 48 hours, Sunday + 24, untill 16.30 on Monday.
Can anybody lend me a hand?
I reorganized your code a bit, to make the logic a little bit clearer, I think this might be what you want.
Edit:
var shippingDate = new Date(bookingDate.getFullYear(), bookingDate.getMonth(), bookingDate.getDay(), 15, 30, 0, 0);
bookingDate.getDay() should be bookingDate.getDate()
var shippingDate = new Date(bookingDate.getFullYear(), bookingDate.getMonth(), bookingDate.getDate(), 15, 30, 0, 0);
jQuery(function($) {
$(document).ready(function() {
var weekday = new Array(7);
weekday[0] = "Zondag";
weekday[1] = "Maandag";
weekday[2] = "Dinsdag";
weekday[3] = "Woensdag";
weekday[4] = "Donderdag";
weekday[5] = "Vrijdag";
weekday[6] = "Zaterdag";
//var bookingDate - the date you book
var bookingDate = new Date();
//var bookingDay - the day you book
var bookingDay = weekday[bookingDate.getDay()];
//var shippingDay - the day you ship
var shippingDay = null;
//var shippingDate - the date you ship
var shippingDate = new Date(bookingDate.getFullYear(), bookingDate.getMonth(), bookingDate.getDate(), 15, 30, 0, 0);
//logic to get shippingDay and shippingDate
if (bookingDay == "Zaterdag") {
shippingDate = shippingDate.setDate(bookingDate.getDate() + 2)
shippingDay = weekday[bookingDate.getDay() + 2];
} else if (bookingDay == "Zondag") {
shippingDate = shippingDate.setDate(bookingDate.getDate() + 1)
shippingDay = weekday[bookingDate.getDay() + 1];
} else {
//if we book before 15:30, we still can catch today's shipping
//otherwise +1 day
if (shippingDate - bookingDate >= 0) {
shippingDay = "Vandaag";
} else {
shippingDate.setDate(bookingDate.getDate() + 1);
shippingDay = weekday[bookingDate.getDay() + 1];
}
}
//you can deal with offdays with similar logic, I don't know what does shippingday = "Vandaag"; means
/*} else if ("" + diff.getHours() + ('0' + diff.getMinutes()).slice(-2) <= 1630 && offdayset == false) {
shippingday = "Vandaag";
} */
//I didn't touch your offday logic, you can fill in the gap
var now = new Date();
var day = now.getDay();
//var day = 6;
var day2 = (now.getDate() < 10 ? '0' : '') + now.getDate();
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var offday = day2 + month;
var offdayset = false;
/* Declare an array. */
var offdays = new Array('2303', '2412', '2512', '3112');
/* Traverse each of value of an array using for loop to
check whether the value is exist in array*/
for (var i = 0; i < offdays.length; i++) {
if (offdays[i] === offday) {
//alert('Value exist');
offdayset = true;
}
}
setInterval(function() {
now = new Date();
var timeleft = shippingDate - now;
var diff = new Date(timeleft);
$("#datecountdown").html("binnen " + diff.getHours() + "u " + diff.getMinutes() + "min " + diff.getSeconds() + "sec");
$("#dateshipping").html(shippingDay);
//below are just for testing purposes
$("#time1").html(offday);
$("#time2").html(offdayset);
$("#time3").html("bookingdate: " + bookingDate);
$("#time4").html("shippingdate: " + shippingDate);
}, 1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="/verzending-bezorging/" class="shippingtimer" title="*wanneer product op voorraad is">
<p class="shippingtimer"> Besteld <span id="datecountdown"></span> = <span id="dateshipping"></span> verzonden*</p>
</a>
<span id="time1"></span>
<br>
<span id="time2"></span>
<br>
<span id="time3"></span>
<br>
<span id="time4"></span>
<br>
<span id="time5"></span>