I want to create a weekly calendar which display the current week and has two buttons nextweek and previousweek. Im able to move to the nextweek, but Im struggling with previousweek button. Need some suggestions for the same. I have used HTML, CSS and Javascript. Im struggling with the logic of previousweek button.
const date = new Date();
function renderCalendar(lastdayofweek)
{
var lastofweek = lastdayofweek;
date.setDate(1);
const monthDays = document.querySelector(".days");
var lastDay = new Date( date.getFullYear(), date.getMonth() + 1, 0).getDate();
const prevLastDay = new Date( date.getFullYear(), date.getMonth(), 0 ).getDate();
const firstDayIndex = date.getDay();
const lastDayIndex = new Date( date.getFullYear(), date.getMonth() + 1, 0 ).getDay();
const nextDays = 7 - lastDayIndex - 1;
const months =
[ 'January', 'February', 'March', 'April', 'May', 'June'
, 'July', 'August', 'September', 'October', 'November', 'December'
];
document.querySelector(".date h1").innerHTML = months[date.getMonth()];
document.querySelector(".date p").innerHTML = new Date().toDateString();
let days = ''
, count = 0
;
if (lastofweek+7 >= lastDay)
{
for (let x = firstDayIndex; x > 0; x--)
{
days += `<div class="prev-date">${prevLastDay - x + 1}</div>`;
count = count+1;
lastofweek = prevLastDay - x + 1;
lastDay = lastofweek;
}
}
const nxtDay = 7 - count - 1;
if (lastofweek == undefined)
{
for (let i = 1; i <= nxtDay+1; i++)
{
if (i === new Date().getDate() && date.getMonth() === new Date().getMonth())
{
days += `<div class="today">${i}</div>`;
}
else
{
days += `<div>${i}</div>`;
lastDayOfWeek = i;
}
count = count+1;
monthDays.innerHTML = days;
}
}
else
{
if (lastofweek+1 > lastDay)
{
lastofweek = 0;
}
var forCount = 0;
for (let i = lastofweek+1; i <= lastofweek+7; i++)
{
if(lastDay >= i && forCount <= nxtDay)
{
if (i === new Date().getDate() && date.getMonth() === new Date().getMonth())
{
days += `<div class="today">${i}</div>`;
}
else
{
days += `<div>${i}</div>`;
lastDayOfWeek = i;
}
count = count+1;
forCount = forCount + 1;
monthDays.innerHTML = days;
}
}
}
if (count < 7)
{
for (let j = 1; j <= nextDays; j++)
{
days += `<div class="next-date">${j}</div>`;
monthDays.innerHTML = days;
}
}
}
document.querySelector(".prev").addEventListener("click", () =>
{
date.setMonth(date.getMonth());
renderCalendar();
});
const lastDay = new Date( date.getFullYear(), date.getMonth() + 1, 0 ).getDate();
document.querySelector(".next").addEventListener("click", () =>
{
if(lastDayOfWeek+7 > lastDay)
{
date.setMonth(date.getMonth()+1);
renderCalendar(lastDayOfWeek);
}
else
{
date.setMonth(date.getMonth());
renderCalendar(lastDayOfWeek);
}
});
renderCalendar();
* {
margin : 0;
padding : 0;
box-sizing : border-box;
font-family : "Quicksand", sans-serif;
}
html {
font-size : 62.5%;
}
.container {
width : 100%;
height : 100vh;
background-color : #12121f;
color : #eee;
display : flex;
justify-content : center;
align-items : center;
}
.calendar {
width : 45rem;
height : 52rem;
background-color : #222227;
box-shadow : 0 0.5rem 3rem #00000066;
}
.month {
width : 100%;
height : 12rem;
background-color : #167e56;
display : flex;
justify-content : space-between;
align-items : center;
padding : 0 2rem;
text-align : center;
text-shadow : 0 0.3rem 0.5rem #00000080;
}
.month i {
font-size : 2.5rem;
cursor : pointer;
}
.month h1 {
font-size : 3rem;
font-weight : 400;
text-transform : uppercase;
letter-spacing : 0.2rem;
margin-bottom : 1rem;
}
.month p {
font-size : 1.6rem;
}
.weekdays {
width : 100%;
height : 5rem;
padding : 0 0.4rem;
display : flex;
align-items : center;
}
.weekdays div {
font-size : 1.5rem;
font-weight : 400;
letter-spacing : 0.1rem;
width : calc(44.2rem / 7);
display : flex;
justify-content : center;
align-items : center;
text-shadow : 0 0.3rem 0.5rem #00000080;
}
.days {
width : 100%;
display : flex;
flex-wrap : wrap;
padding : 0.2rem;
}
.days div {
font-size : 1.4rem;
margin : 0.3rem;
width : calc(40.2rem / 7);
height : 5rem;
display : flex;
justify-content : center;
align-items : center;
text-shadow : 0 0.3rem 0.5rem #00000080;
transition : background-color 0.2s;
}
.days div:hover:not(.today) {
background-color : #262626;
border : 0.2rem solid #777;
cursor : pointer;
}
.today {
background-color : #167e56;
}
/* --- --- ---
.prev-date,
.next-date {
opacity : 0.5;
}
--- --- --- */
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" >
<link href="https://fonts.googleapis.com/css2?family=Quicksand:wght#300;400;500;600;700&display=swap" rel="stylesheet" >
<input type="hidden" name="dates" class="dates" value="<?= $dates ?>" >
<div class="container">
<div class="calendar">
<div class="month">
<i class="fas fa-angle-left prev"></i>
<div class="date">
<h1></h1>
<p></p>
</div>
<i class="fas fa-angle-right next"></i>
</div>
<div class="weekdays">
<div>Sun</div>
<div>Mon</div>
<div>Tue</div>
<div>Wed</div>
<div>Thu</div>
<div>Fri</div>
<div>Sat</div>
</div>
<div class="days"></div>
</div>
</div>
Related
I make a datepicker on vue3, When choosing two dates, I need the days between the selected dates to be hover. I use the "indexOf" method, but the desired result is not obtained
<div
v-for="date in daysInMonth(currentYear, currentMonthInNumber, firstDay, lastDay)"
:key="date"
ref="date"
class="day"
:class="{ active: date === firstDay || date === lastDay, between: between.indexOf(date)}"
#click="choosingDates(date)" > {{ date }} </div>
<script>
firstDay: false,
between: [],
lastDay: false,
firstDaySelected: false,
};
},
methods: {
choosingDates(date) {
if (this.firstDay === false) {
this.firstDay = date;
} else if (this.lastDay === false) {
this.lastDay = date;;
}
},
With this code, "between" hover all days of the month (css styles are written)
:class="{ between: between.indexOf(date)} "
what i do wrong
Try this :
<template>
<div class="datepicker">
<div class="month-header">
<i class="prev-month" #click="prevMonth"></i>
{{ currentMonth }} {{ currentYear }}
<i class="next-month" #click="nextMonth"></i>
</div>
<div class="weekdays">
<div class="weekday" v-for="weekday in weekdays" :key="weekday">
{{ weekday }}
</div>
</div>
<div class="days">
<div
v-for="date in daysInMonth(
currentYear,
currentMonthInNumber,
firstDay,
lastDay
)"
:key="date"
class="day"
:class="{
active: date === firstDay || date === lastDay,
between: between.includes(date),
}"
#click="chooseDate(date)"
>
{{ date }}
</div>
</div>
{{ between }}
</div>
</template>
<script>
export default {
data() {
return {
weekdays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
months: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
],
currentMonth: "",
currentMonthInNumber: "",
currentYear: "",
firstDay: false,
between: [],
lastDay: false,
};
},
mounted() {
const date = new Date();
this.currentMonth = this.months[date.getMonth()];
this.currentMonthInNumber = date.getMonth();
this.currentYear = date.getFullYear();
},
methods: {
prevMonth() {
this.currentMonthInNumber--;
if (this.currentMonthInNumber < 0) {
this.currentMonthInNumber = 11;
this.currentYear--;
}
this.currentMonth = this.months[this.currentMonthInNumber];
},
nextMonth() {
this.currentMonthInNumber++;
if (this.currentMonthInNumber > 11) {
this.currentMonthInNumber = 0;
this.currentYear++;
}
this.currentMonth = this.months[this.currentMonthInNumber];
},
daysInMonth(year, month, firstDay, lastDay) {
let date = new Date(year, month, 1);
let days = [];
while (date.getMonth() === month) {
days.push(date.getDate());
date.setDate(date.getDate() + 1);
}
return days;
},
chooseDate(date) {
if (this.firstDay === false) {
this.firstDay = date;
} else if (this.lastDay === false) {
this.lastDay = date;
this.setBetween();
} else {
this.firstDay = date;
this.lastDay = false;
this.between = [];
}
},
setBetween() {
if (this.firstDay > this.lastDay) {
[this.firstDay, this.lastDay] = [this.lastDay, this.firstDay];
}
let date = new Date(
this.currentYear,
this.currentMonthInNumber,
this.firstDay
);
while (date.getDate() <= this.lastDay) {
this.between.push(date.getDate());
date.setDate(date.getDate() + 1);
}
},
},
};
</script>
<style scoped>
.datepicker {
background-color: #fff;
border-radius: 5px;
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
padding: 20px;
text-align: center;
}
.month-header {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
}
.prev-month,
.next-month {
cursor: pointer;
}
.weekdays {
display: flex;
}
.weekday {
flex: 1;
font-weight: bold;
padding: 10px 0;
}
.days {
display: grid;
grid-template-columns: repeat(7, 1fr);
grid-gap: 10px;
margin-top: 20px;
}
.day {
background-color: #fff;
border: 1px solid #ddd;
border-radius: 5px;
cursor: pointer;
height: 40px;
line-height: 40px;
text-align: center;
user-select: none;
}
.day.active {
background-color: #3c8dbc;
color: #fff;
}
.day.between {
background-color: #ddd;
}
</style>
NOTE-I'm new to JS and in this code, 24 hour clock runs and when I tap on 12 hour clock format
button it won't replace with 24 hour clock format. basically the button wont work or it wont
replace the clock format plz help
I used a window. Onload function which runs the 24 hour format clock and when I tap on 12 hour format clock button it wont replace
just run the code u'll understand what I mean
the only thing I want to achieve in this code is a clock which have two button 1st:12 hour format 2nd:24 hour format,
to change clock format on a tap
window.onload = (event) => {
clock_24();
};
function clock_24() {
let a;
let date;
let time;
const options = {
day: 'numeric',
month: 'long',
year: 'numeric'
};
setInterval(() => {
a = new Date();
date = a.toLocaleDateString(undefined, options);
let hours = String(a.getHours()).padStart(2, '0');
let min = String(a.getMinutes()).padStart(2, '0');
let sec = String(a.getSeconds()).padStart(2, '0');
let milli = a.getMilliseconds();
time = hours + ':' + min + ':' + sec + ':' + milli;
document.getElementById('time').innerHTML = time
document.getElementById('date').innerHTML = date
}, 1);
// foramt-change
document.getElementById("format").innerHTML = "24 Hour format";
document.getElementById("format").style.fontSize = "32px";
document.getElementById("format").style.fontfamily = 'Times New Roman';
console.log('24_loaded');
}
// onclick - event-12-hour-format-clock
// time-12f
function clock_12() {
setInterval(() => {
var date = new Date();
var hh_12 = date.getHours() > 12 ? date.getHours() - 12 : date.getHours();
var session_12 = date.getHours() >= 12 ? "PM" : "AM";
hh_12 = hh_12 < 10 ? "0" + hh_12 : hh_12;
var mm_12 = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var ss_12 = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
tt_12 = hh_12 + ":" + mm_12 + ":" + ss_12 + " " + session_12;
document.getElementById('time').innerHTML = tt_12
// date-12f
const options = {
day: 'numeric',
month: 'long',
year: 'numeric'
};
date = date.toLocaleDateString(undefined, options);
document.getElementById('date').innerHTML = date
}, 1000);
// foramt-change
document.getElementById("format").innerHTML = "12 Hour format";
document.getElementById("format").style.fontSize = "32px";
document.getElementById("format").style.fontfamily = 'Times New Roman';
console.log('12_loaded');
}
* {
margin: 0;
padding: 0;
}
.t-d-cont {
background-color: gray;
margin: 50px;
padding: 50px;
}
#format {
border-left: 2px solid rgb(70, 166, 239);
margin-bottom: 20px;
padding-left: 20px;
font-weight: bold;
}
.redline {
border-left: 2px solid red;
width: 100%;
padding-left: 20px;
}
.time-box {
margin-bottom: 50px;
}
#time {
font-family: 'Rokkitt', serif;
font-size: 45px;
}
.date-box {
margin-bottom: 30px;
}
#date {
font-family: 'Rokkitt', serif;
font-size: 45px;
}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropbtn-2 {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
margin-left: 15px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- font link -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Rokkitt:wght#100&display=swap" rel="stylesheet">
</head>
<body>
<!-- time and date container -->
<div class="t-d-cont">
<div id="format">
<h1>24 Hour format</h1>
</div>
<div class="redline ">
<div class="time-box">
<h1>Current Time: <span id="time"></span></h1>
</div>
<div class="date-box">
<h1> Today's Date: <span id="date"></span></h1>
</div>
</div>
<!-- 24 hour-button -->
<div class="dropdown">
<button class="dropbtn-2" onclick="clock_24();">24-hour-format</button>
</div>
<!-- 12 hour-button -->
<div class="dropdown">
<button class="dropbtn" onclick="clock_12();">12-hour-format</button>
</div>
</div>
</body>
</div>
</html>
When you switch the clocks, you need to stop the interval timer that's displaying using the previous format. Otherwise they both keep running, and one will overwrite the other.
Use a variable outside the functions to hold the current interval timer ID, so you can stop it with clearInterval().
window.onload = (event) => {
clock_24();
};
let timer;
function clock_24() {
let a;
let date;
let time;
const options = {
day: 'numeric',
month: 'long',
year: 'numeric'
};
clearInterval(timer);
timer = setInterval(() => {
a = new Date();
date = a.toLocaleDateString(undefined, options);
let hours = String(a.getHours()).padStart(2, '0');
let min = String(a.getMinutes()).padStart(2, '0');
let sec = String(a.getSeconds()).padStart(2, '0');
let milli = a.getMilliseconds();
time = hours + ':' + min + ':' + sec + ':' + milli;
document.getElementById('time').innerHTML = time
document.getElementById('date').innerHTML = date
}, 1);
// foramt-change
document.getElementById("format").innerHTML = "24 Hour format";
document.getElementById("format").style.fontSize = "32px";
document.getElementById("format").style.fontfamily = 'Times New Roman';
console.log('24_loaded');
}
// onclick - event-12-hour-format-clock
// time-12f
function clock_12() {
clearInterval(timer);
timer = setInterval(() => {
var date = new Date();
var hh_12 = date.getHours() > 12 ? date.getHours() - 12 : date.getHours();
var session_12 = date.getHours() >= 12 ? "PM" : "AM";
hh_12 = hh_12 < 10 ? "0" + hh_12 : hh_12;
var mm_12 = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var ss_12 = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
tt_12 = hh_12 + ":" + mm_12 + ":" + ss_12 + " " + session_12;
document.getElementById('time').innerHTML = tt_12
// date-12f
const options = {
day: 'numeric',
month: 'long',
year: 'numeric'
};
date = date.toLocaleDateString(undefined, options);
document.getElementById('date').innerHTML = date
}, 1000);
// foramt-change
document.getElementById("format").innerHTML = "12 Hour format";
document.getElementById("format").style.fontSize = "32px";
document.getElementById("format").style.fontfamily = 'Times New Roman';
console.log('12_loaded');
}
* {
margin: 0;
padding: 0;
}
.t-d-cont {
background-color: gray;
margin: 50px;
padding: 50px;
}
#format {
border-left: 2px solid rgb(70, 166, 239);
margin-bottom: 20px;
padding-left: 20px;
font-weight: bold;
}
.redline {
border-left: 2px solid red;
width: 100%;
padding-left: 20px;
}
.time-box {
margin-bottom: 50px;
}
#time {
font-family: 'Rokkitt', serif;
font-size: 45px;
}
.date-box {
margin-bottom: 30px;
}
#date {
font-family: 'Rokkitt', serif;
font-size: 45px;
}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropbtn-2 {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
margin-left: 15px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- font link -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Rokkitt:wght#100&display=swap" rel="stylesheet">
</head>
<body>
<!-- time and date container -->
<div class="t-d-cont">
<div id="format">
<h1>24 Hour format</h1>
</div>
<div class="redline ">
<div class="time-box">
<h1>Current Time: <span id="time"></span></h1>
</div>
<div class="date-box">
<h1> Today's Date: <span id="date"></span></h1>
</div>
</div>
<!-- 24 hour-button -->
<div class="dropdown">
<button class="dropbtn-2" onclick="clock_24();">24-hour-format</button>
</div>
<!-- 12 hour-button -->
<div class="dropdown">
<button class="dropbtn" onclick="clock_12();">12-hour-format</button>
</div>
</div>
</body>
</div>
</html>
I have 2 issues with my alarm clock.
1)When the hour is increased or decreased to over 12, I want to switch from AM to PM. The problem is that where I call the today.getHours();, it's inside a different function. My increment button function (to increase/decrease) is outside that function and when moved inside the clock function holding today.getHours(), doesn't work, so I can't say when hours is greater than 12, switch to PM. And it seems redundant to call getHours again. Does anyone have any recommendations on how to fix this in vanilla JS? Is there a better way to do it?
2)When clicked, the minute decrease increment button gives negative values. I know this probably has a simple solution but I think I've been staring at it for too long to see it.
//Select Elements
const alarm_time = document.getElementById('alarmTime');
const set_alarm = document.getElementById('setAlarm');
const alarm_alert = document.getElementById('alarmAlert');
const hr_increase= document.getElementById('hourIncrease');
const hr_decrease = document.getElementById('hourDecrease');
const min_increase= document.getElementById('minuteIncrease');
const min_decrease = document.getElementById('minuteDecrease');
const increment = document.querySelectorAll('.increment');
//Variables
let hr;
let min;
let TOD;
let alarmHr=0;
let alarmMin=0;
let alarmTOD="AM";
let alarmActive=false;
//Alarm Sound
let sound = new Audio("https://res.cloudinary.com/saveallthethings/video/upload/v1565033348/Free%20Music%20Downloads/bensound-hey_vunrwo.mp3");
//Alarm Function
if (alarmHr== hr && parseInt(alarmMin) == min && alarmTOD == TOD){
sound.play();
card.classList.add("blinkingAlarm");
}
//Get Time
function clock(){
//Display Greeting, Time and Date
let today = new Date();
let year = today.getFullYear();
let date = today.getDate();
let hours = today.getHours();
let minutes = today.getMinutes();
//Specify Am or PM, and populate greeting
if (hours >= 17){
timeofDay = "PM";
} else if (hours >= 12 && hours < 17){
timeofDay = "PM";
} else {
timeofDay = " AM";
}
//Convert Hours to 12hr Format
if (hours>12){
hours = hours - 12;
}
else if (hours===0){
hours = 12;
}
//For single digit minutes, add a zero
if (minutes<10){
minutes = "0" + minutes;
}
else {
minutes = minutes;
}
if (alarm_time.classList.contains("blinkingText")){
alarm_time.innerHTML = (alarmHr + ":" + alarmMin + alarmTOD);
}else{alarm_time.innerHTML = (hours + ":" + minutes + timeofDay);}
}//Closing Brackets for clock fnc
//Set Interval to Update Time
setInterval('clock()', 500);
//Count Clicks on Set Alarm Btn
let clickCounter = 0;
set_alarm.onclick = function() {
clickCounter += 1;
//Second Click sets the alarm, says "Alarm set to"
if((clickCounter % 2) === 0){
alarm_time.classList.remove("blinkingText");
alarmActive = true;
if (alarmHr == 0 && alarmMin == 0){
alarm_alert.innerHTML = "no alarm set";
}else{
alarm_alert.innerHTML = "alarm set for "+ alarmHr +":" + alarmMin + alarmTOD;
}
//Loop that disables and hides buttons
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.remove("visibility");
hourDecrease.classList.remove("visibility");
minuteIncrease.classList.remove("visibility");
minuteDecrease.classList.remove("visibility");
document.getElementById("hourIncrease").disabled = true;
document.getElementById("hourDecrease").disabled = true;
document.getElementById("minuteIncrease").disabled = true;
document.getElementById("minuteDecrease").disabled = true;
}
} else {
alarm_time.classList.add("blinkingText");
//Loop Over the Node List for increment
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.add("visibility");
hourDecrease.classList.add("visibility");
minuteIncrease.classList.add("visibility");
minuteDecrease.classList.add("visibility");
document.getElementById("hourIncrease").disabled = false;
document.getElementById("hourDecrease").disabled = false;
document.getElementById("minuteIncrease").disabled = false;
document.getElementById("minuteDecrease").disabled = false;
}
}
};
//Turn off alarm
dismiss.onclick = function() {
if(alarmActive = "true"){
alarmActive ="false"
alarmHr = 0;
alarmMin = 0;
alarmTOD = "AM";
alarm_alert.innerHTML = "no alarm set";
sound.pause();
alarm_time.classList.remove("blinkingText");
//Loop that disables and hides buttons
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.remove("visibility");
hourDecrease.classList.remove("visibility");
minuteIncrease.classList.remove("visibility");
minuteDecrease.classList.remove("visibility");
document.getElementById("hourIncrease").disabled = true;
document.getElementById("hourDecrease").disabled = true;
document.getElementById("minuteIncrease").disabled = true;
document.getElementById("minuteDecrease").disabled = true;
}
}
};
hr_increase.onclick = function() {
alarmHr++;
if (alarmHr > 12){
alarmHr= alarmHr - 12;
}
}
hr_decrease.onclick = function() {
alarmHr--;
if (alarmHr <= 0){
alarmHr= alarmHr + 12;
}
console.log(alarmHr);};
min_increase.onclick = function() {
alarmMin++;
if (alarmMin < 10){
alarmMin= "0" + alarmMin;
}
if(alarmMin > 59){
alarmMin= alarmMin-60 ;
}
if(alarmMin == 0){
alarmMin= "00";
}
}
min_decrease.onclick = function() {
alarmMin--;
if (alarmMin < 10){
alarmMin= "0" + minutes;
}
if (alarmMin < 0){
alarmMin= alarmMin % 60;
}
};
#import url('https://fonts.googleapis.com/css?family=Montserrat:900|Open+Sans:800|Source+Sans+Pro:300');
html, body {
height: 100%;
font-family: 'Source Sans Pro', sans-serif;
font-size:15px;
}
.card_container{
height:100vh;
}
.center{
display:flex;
justify-content:center;
align-items:center;
}
.card{
border-radius:15px;
background-color: rgba(254, 253, 253,0.8);
box-shadow: 0px 0px 51px -3px rgba(0,0,0,0.13);
max-width:22rem;
border:solid rgba(254, 253, 253,0.8) 0.1px;
}
.blinkingAlarm{
animation:blinkingAlarm 1.2s ease-in-out infinite;
}
#keyframes blinkingAlarm{
50%{
border:solid white 7px;}
}
.card_inner{
border-radius:15px;
margin:.75rem;
}
.card_currentContainer{
border-radius:15px;
margin-bottom:1rem;
}
.card_alarmContainer {
color:#7E7E7E;
background:#fff;
text-align:center;
}
.card_alarmContainer{
flex-direction:column;
border-radius:15px;
}
.alarmOptions{
display:flex;
color:#7E7E7E;
padding-top:.5rem;
padding-bottom:.5rem;
}
.blinkingText{
animation:blinkingText 1.6s linear infinite;
}
#keyframes blinkingText{
50%{opacity:0.3;}
}
.setBox{
flex-direction:column;
padding-left:.5rem;
padding-right:.5rem;
padding-top:0;
}
.button {
display:block;
border-style:none;
margin: 0px 0px;
padding:0px;
}
.increment{
font-size:1rem;
border:none;
background: rgba(254, 253, 253,0.8);
color:#7E7E7E;
font-family: 'Source Sans Pro', sans-serif;
cursor: pointer;
visibility:hidden;
}
.increment:hover{
cursor:pointer;
color:black;
border-style:none;
}
.visibility{
visibility:visible;
}
.alarmBox{
padding-bottom:.2rem;
}
.alarmTime{
font-size:2rem;
line-height:1rem;
padding-top:.7rem;
}
.alarmAlert{
font-size:.8rem;
text-transform:uppercase;
padding-top:.5rem;
}
.card_buttonsContainer{
width:100%;
margin:1rem 0rem;
justify-content:space-between;
flex-wrap:wrap;
}
.btn{
height:3rem;
width:8rem;
}
#setAlarm{
transition: .2s;
color:#fff;
cursor:pointer;
border-radius:15px;
background: linear-gradient(to left, #ff7e5f , #feb47b);
padding-right:.5rem;
padding-left:.5rem;
font-size:1.5rem;
margin-right:0.3rem;
}
#setAlarm:hover{
border-radius:20px;
opacity: .8;
}
#dismiss{
transition: .2s;
font-size:1.5rem;
color:#fff;
border-radius:15px;
cursor:pointer;
background: linear-gradient(to left, #64B1F2 , #00DBF3);
padding-right:.5rem;
padding-left:.5rem;
margin-left:0.3rem;
}
#dismiss:hover{
border-radius:20px;
opacity: .8;
}
/***Media Queries****/
#media only screen and (max-width:332px) {
.current_greetings{
text-align:center;
}
.card_buttonsContainer{
justify-content:center;
}
.btn{
margin-bottom:.5rem;
}
}
<div class="card_container center">
<div class ="card">
<div class="card_inner">
<div class="card_alarmContainer center">
<div class="alarmOptions ">
<div class="setBox center">
<button class="increment center" id="hourIncrease" disabled>+</button>
<button class="increment center" id="hourDecrease" disabled>−</button>
</div>
<div class="alarmBox">
<div class="alarmTime center" id="alarmTime"></div>
<div class="alarmAlert" id="alarmAlert">no alarm set</div>
</div>
<div class="setBox center">
<button class="increment center" id="minuteIncrease" disabled>+</button>
<button class="increment center" id="minuteDecrease" disabled>−</button>
</div>
</div>
</div>
<div class="card_buttonsContainer center">
<div class ="buttonBox center">
<div class="btn center" id="setAlarm">Set Alarm</div>
</div>
<div class ="buttonBox center">
<div class="btn center" id="dismiss">Dismiss</div>
</div>
</div>
</div>
</div>
</div>
In your code you need to increase and decrease the hour on the minute change. I also suggest pulling the hour increase and hour decrease out into functions (I have sample code of a working solution) so you can use them in the minute increase and decrease functions to increase or decrease the time. I also suggest using a function for the alarm time of day change so you can use it in both your hour increase and hour decrease functions. Your initial value for alarm hour was 0 but there is no 0 hour. I suggest starting with 12 for the alarm hour. I updated all of this in my sample code
The way you can update the TOD is in the hour increase check if the new hour is 12 and then toggle the TOD. In the decrease you check if the new hour is 11 and then toggle the TOD. See my sample working code!
//Select Elements
const alarm_time = document.getElementById('alarmTime');
const set_alarm = document.getElementById('setAlarm');
const alarm_alert = document.getElementById('alarmAlert');
const hr_increase= document.getElementById('hourIncrease');
const hr_decrease = document.getElementById('hourDecrease');
const min_increase= document.getElementById('minuteIncrease');
const min_decrease = document.getElementById('minuteDecrease');
const increment = document.querySelectorAll('.increment');
//Variables
let hr;
let min;
let TOD;
let alarmHr=12;
let alarmMin=0;
let alarmTOD="AM";
let alarmActive=false;
//Alarm Sound
let sound = new Audio("https://res.cloudinary.com/saveallthethings/video/upload/v1565033348/Free%20Music%20Downloads/bensound-hey_vunrwo.mp3");
//Alarm Function
if (alarmHr== hr && parseInt(alarmMin) == min && alarmTOD == TOD){
sound.play();
card.classList.add("blinkingAlarm");
}
function toggleAlarmTOD() {
if(alarmTOD === "AM") {
alarmTOD = "PM"
} else {
alarmTOD = "AM"
}
}
function increaseHr() {
alarmHr++;
if(alarmHr === 12) {
toggleAlarmTOD();
} else if (alarmHr > 12){
alarmHr = alarmHr - 12;
}
}
function decreaseHr() {
alarmHr--;
if(alarmHr <= 0) {
alarmHr = alarmHr + 12;
} else if(alarmHr === 11) {
toggleAlarmTOD();
}
}
//Get Time
function clock(){
//Display Greeting, Time and Date
let today = new Date();
let year = today.getFullYear();
let date = today.getDate();
let hours = today.getHours();
let minutes = today.getMinutes();
//Specify Am or PM, and populate greeting
if(hours >= 12){
timeofDay = "PM";
} else {
timeofDay = " AM";
}
//Convert Hours to 12hr Format
if (hours>12){
hours = hours - 12;
}
else if (hours===0){
hours = 12;
}
//For single digit minutes, add a zero
if (minutes < 10) {
minutes = "0" + minutes;
}
else {
minutes = minutes;
}
if (alarm_time.classList.contains("blinkingText")){
alarm_time.innerHTML = (alarmHr + ":" + (alarmMin < 10 ? "0" + alarmMin : alarmMin) + alarmTOD);
}else{alarm_time.innerHTML = (hours + ":" + minutes + timeofDay);}
}//Closing Brackets for clock fnc
//Set Interval to Update Time
setInterval('clock()', 500);
//Count Clicks on Set Alarm Btn
let clickCounter = 0;
set_alarm.onclick = function() {
clickCounter++;
//Second Click sets the alarm, says "Alarm set to"
if((clickCounter % 2) === 0){
alarm_time.classList.remove("blinkingText");
alarmActive = true;
if (alarmHr == 0 && alarmMin == 0){
alarm_alert.innerHTML = "no alarm set";
}else{
alarm_alert.innerHTML = "alarm set for " + alarmHr + ":" + (alarmMin < 10 ? "0" + alarmMin : alarmMin) + alarmTOD;
}
//Loop that disables and hides buttons
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.remove("visibility");
hourDecrease.classList.remove("visibility");
minuteIncrease.classList.remove("visibility");
minuteDecrease.classList.remove("visibility");
document.getElementById("hourIncrease").disabled = true;
document.getElementById("hourDecrease").disabled = true;
document.getElementById("minuteIncrease").disabled = true;
document.getElementById("minuteDecrease").disabled = true;
}
} else {
alarm_time.classList.add("blinkingText");
//Loop Over the Node List for increment
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.add("visibility");
hourDecrease.classList.add("visibility");
minuteIncrease.classList.add("visibility");
minuteDecrease.classList.add("visibility");
document.getElementById("hourIncrease").disabled = false;
document.getElementById("hourDecrease").disabled = false;
document.getElementById("minuteIncrease").disabled = false;
document.getElementById("minuteDecrease").disabled = false;
}
}
};
//Turn off alarm
dismiss.onclick = function() {
if(alarmActive = "true") {
alarmActive ="false"
alarmHr = 12;
alarmMin = 0;
alarmTOD = "AM";
alarm_alert.innerHTML = "no alarm set";
sound.pause();
alarm_time.classList.remove("blinkingText");
//Loop that disables and hides buttons
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.remove("visibility");
hourDecrease.classList.remove("visibility");
minuteIncrease.classList.remove("visibility");
minuteDecrease.classList.remove("visibility");
document.getElementById("hourIncrease").disabled = true;
document.getElementById("hourDecrease").disabled = true;
document.getElementById("minuteIncrease").disabled = true;
document.getElementById("minuteDecrease").disabled = true;
}
}
};
hr_increase.onclick = function() {
increaseHr();
}
hr_decrease.onclick = function() {
decreaseHr();
};
min_increase.onclick = function() {
alarmMin++;
if(alarmMin > 59){
alarmMin = 0;
increaseHr();
}
}
min_decrease.onclick = function() {
alarmMin--;
if (alarmMin < 0){
alarmMin = 59;
decreaseHr();
}
};
#import url('https://fonts.googleapis.com/css?family=Montserrat:900|Open+Sans:800|Source+Sans+Pro:300');
html, body {
height: 100%;
font-family: 'Source Sans Pro', sans-serif;
font-size:15px;
}
.card_container{
height:100vh;
}
.center{
display:flex;
justify-content:center;
align-items:center;
}
.card{
border-radius:15px;
background-color: rgba(254, 253, 253,0.8);
box-shadow: 0px 0px 51px -3px rgba(0,0,0,0.13);
max-width:22rem;
border:solid rgba(254, 253, 253,0.8) 0.1px;
}
.blinkingAlarm{
animation:blinkingAlarm 1.2s ease-in-out infinite;
}
#keyframes blinkingAlarm{
50%{
border:solid white 7px;}
}
.card_inner{
border-radius:15px;
margin:.75rem;
}
.card_currentContainer{
border-radius:15px;
margin-bottom:1rem;
}
.card_alarmContainer {
color:#7E7E7E;
background:#fff;
text-align:center;
}
.card_alarmContainer{
flex-direction:column;
border-radius:15px;
}
.alarmOptions{
display:flex;
color:#7E7E7E;
padding-top:.5rem;
padding-bottom:.5rem;
}
.blinkingText{
animation:blinkingText 1.6s linear infinite;
}
#keyframes blinkingText{
50%{opacity:0.3;}
}
.setBox{
flex-direction:column;
padding-left:.5rem;
padding-right:.5rem;
padding-top:0;
}
.button {
display:block;
border-style:none;
margin: 0px 0px;
padding:0px;
}
.increment{
font-size:1rem;
border:none;
background: rgba(254, 253, 253,0.8);
color:#7E7E7E;
font-family: 'Source Sans Pro', sans-serif;
cursor: pointer;
visibility:hidden;
}
.increment:hover{
cursor:pointer;
color:black;
border-style:none;
}
.visibility{
visibility:visible;
}
.alarmBox{
padding-bottom:.2rem;
}
.alarmTime{
font-size:2rem;
line-height:1rem;
padding-top:.7rem;
}
.alarmAlert{
font-size:.8rem;
text-transform:uppercase;
padding-top:.5rem;
}
.card_buttonsContainer{
width:100%;
margin:1rem 0rem;
justify-content:space-between;
flex-wrap:wrap;
}
.btn{
height:3rem;
width:8rem;
}
#setAlarm{
transition: .2s;
color:#fff;
cursor:pointer;
border-radius:15px;
background: linear-gradient(to left, #ff7e5f , #feb47b);
padding-right:.5rem;
padding-left:.5rem;
font-size:1.5rem;
margin-right:0.3rem;
}
#setAlarm:hover{
border-radius:20px;
opacity: .8;
}
#dismiss{
transition: .2s;
font-size:1.5rem;
color:#fff;
border-radius:15px;
cursor:pointer;
background: linear-gradient(to left, #64B1F2 , #00DBF3);
padding-right:.5rem;
padding-left:.5rem;
margin-left:0.3rem;
}
#dismiss:hover{
border-radius:20px;
opacity: .8;
}
/***Media Queries****/
#media only screen and (max-width:332px) {
.current_greetings{
text-align:center;
}
.card_buttonsContainer{
justify-content:center;
}
.btn{
margin-bottom:.5rem;
}
}
<div class="card_container center">
<div class ="card">
<div class="card_inner">
<div class="card_alarmContainer center">
<div class="alarmOptions ">
<div class="setBox center">
<button class="increment center" id="hourIncrease" disabled>+</button>
<button class="increment center" id="hourDecrease" disabled>−</button>
</div>
<div class="alarmBox">
<div class="alarmTime center" id="alarmTime"></div>
<div class="alarmAlert" id="alarmAlert">no alarm set</div>
</div>
<div class="setBox center">
<button class="increment center" id="minuteIncrease" disabled>+</button>
<button class="increment center" id="minuteDecrease" disabled>−</button>
</div>
</div>
</div>
<div class="card_buttonsContainer center">
<div class ="buttonBox center">
<div class="btn center" id="setAlarm">Set Alarm</div>
</div>
<div class ="buttonBox center">
<div class="btn center" id="dismiss">Dismiss</div>
</div>
</div>
</div>
</div>
</div>
I am trying to count the number of times each value occurs for 'classtext' which is in data.items
However, by adding a function below to do that for each new inputted classtext on button click, I get 0 returned, even if I previously input several 'test' in the classtext field. I am very new in vuejs so obviously I am doing something wrong.
The code looks like this:
<!DOCTYPE html>
<html>
<script src="https://vuejs.org/js/vue.js"></script>
<style>
/* Vue List Item transition */
.list-item-enter-active,
.list-item-leave-active {
transition: opacity 0.3s, -webkit-transform 0.3s;
transition: opacity 0.3s, transform 0.3s;
transition: opacity 0.3s, transform 0.3s, -webkit-transform 0.3s;
-webkit-transform-origin: left center;
transform-origin: left center;
}
.list-item-enter,
.list-item-leave-to {
opacity: 0;
-webkit-transform: scale(0.5);
transform: scale(0.5);
}
/* //////////////////////////////////////// */
/* Basic Styles */
html {
background: #eee;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.list {
background: #FFF;
margin: auto;
padding: 1em 1em 1em;
box-shadow: 0 5px 30px rgba(0, 0, 0, 0.2);
}
.list :last-child {
margin-bottom: 0;
}
.list__ul {
list-style-type: none;
margin: 0;
padding: 0;
}
.list__input {
display: flex;
margin-bottom: 0.5em;
}
.list__item {
display: block;
margin-bottom: 0.25em;
}
</style>
</head>
<body>
<div id="example-1" class="list">
<div class="list__input" #keydown.enter="add">
<button v-on:click="count">+</button>
<input v-model="newBeneficiary" placeholder="Add beneficiary" />
<input v-model="newClass" placeholder="Add new task topic" />
<input v-model="newItem" placeholder="Add new task text" />
</div>
<transition-group name="list-item" tag="ul" class="list__ul">
<li class="list__item" v-for="item in items" :key="item">
Timestamp: {{ item.timestamp }} <br />
Beneficiary: {{ item.beneficiarytext }} <br />
Topic: {{ item.classtext }} <br />
Task: {{ item.message }}
</li>
</transition-group>
</div>
</body>
<script>
/**
* Return a timestamp with the format "m/d/yy h:MM:ss TT"
* #type {Date}
*/
function timeStamp() {
var now = new Date();
var date = [ now.getMonth() + 1, now.getDate(), now.getFullYear() ];
var time = [ now.getHours(), now.getMinutes(), now.getSeconds() ];
var suffix = ( time[0] < 12 ) ? "AM" : "PM";
time[0] = ( time[0] < 12 ) ? time[0] : time[0] - 12;
time[0] = time[0] || 12;
for ( var i = 1; i < 3; i++ ) {
if ( time[i] < 10 ) {
time[i] = "0" + time[i];
}
}
return date.join("/") + " " + time.join(":") + " " + suffix;
}
var app = new Vue({
el: '#example-1',
data: {
items: [
/*{ timestamp:'testdate', beneficiarytext: 'TestBeneficiary', classtext: 'TestTopic', message: 'TestMessage' }*/
]
},
methods: {
/* MIGHT BE USED LATER TO DELETE TASKS
remove: function(item){
this.items.splice( this.items.indexOf(item), 1 );
},
*/
add: function(){
this.items.unshift({ timestamp: timeStamp(), beneficiarytext: this.newBeneficiary, classtext: this.newClass, message: this.newItem });
this.newItem = '';
console.log(this.items);
},
count: function() {
var counting = this.items.reduce(function (n, class1) {
return n + (class1.classtext == this.newClass);
}, 0)}
}
})
</script>
</body>
</html>
You didn't bind this to the reducer function. Use
this.items.reduce((n, class1) => { ... })
or
this.items.reduce(function (n, class1) { ... }.bind(this))
See How does the “this” keyword work?.
The compute the counts for each classtext in the array:
this.items.reduce((map, item) => {
map.set(item.classtext, (map.get(item.classtext) || 0) + 1)
return map
}, new Map())
// Returns Map of (classtext, count) pairs:
// {
// apple => 2,
// banana => 6,
// }
I'm trying to get a countdown timer to work on my web page, but its not working, and I can't figure out why. I don't know if its because I linked it wrong in my HTML or if its because I missed something in my code. Any help would be appreciate.
"use strict";
setInterval(function() { ... }, 1000); // 1000 milliseconds = 1 second
// Function to display current date / time on the site
setInterval(function displayTimeAndDate() {
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
var date = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var amOrPm;
// Check if it's a.m or p.m
if (hours < 12) {
amOrPm = "a.m";
} else {
amOrPm = "p.m";
}
document.getElementById('date').innerText = date + ":" + month + ":" + year;
document.getElementById('time').innerText = hours + ":" + minutes + ":" + seconds + " " + amOrPm;
}, 1000);
setInterval(function countdown() {
// Set the desired date (American date format: Month/Day/Year) to countdown to and the current date
var endDate = new Date('07/04/2018 09:00 PM');
var currentDate = new Date();
// Get the "distance" between the dates
var distance = endDate - currentDate;
// Initialize days, hours, minutes and seconds
var oneSecond = 1000; // 1000 milliseconds = 1 second
var oneMinute = oneSecond * 60;
var oneHour = oneMinute * 60;
var oneDay = oneHour * 24;
// Get distance in days, hours, minutes and seconds
var days = Math.floor(distance / oneDay);
var hours = Math.floor((distance % oneDay) / oneHour);
var minutes = Math.floor((distance % oneHour) / oneMinute);
var seconds = Math.floor((distance % oneMinute) / oneSecond);
// Place 0 before the numbers if the are lower than 10
hours = (hours < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
document.getElementById('dLeft').innerText = days;
document.getElmentById('hLeft').innerText = hours;
document.getElementById('mLeft').innerText = minutes;
document.getElementById('sLeft').innerText = seconds;
}, 1000);
<!DOCTYPE html>
<html lang="en">
<head>
<!--
New Perspectives on HTML5 and CSS3, 7th Edition
Tutorial 9
Review Assignment
Tulsa's Summer Party
Author:
Date:
Filename: tny_july.html
-->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Tulsa's Summer Party</title>
<link href="tny_base.css" rel="stylesheet" />
<link href="tny_layout.css" rel="stylesheet" />
<script src="tny_timer.js" defer></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<header>
<nav class="horizontal">
<ul>
<li>News</li>
<li>Night Beat</li>
<li>Tulsa Times</li>
<li>Calendar</li>
<li>City Links</li>
</ul>
</nav>
<img src="tny_banner2.png" id="logoImg" alt="" />
<h1>Tulsa's<br />Summer Party</h1>
<h2 id="timeHeading">Welcome to Tulsa</h2>
<div id="currentTime"><span>11/3/2017</span><span>2:45:12 p.m.</span></div>
</header>
<article>
<section>
<h1>Countdown to the Fireworks</h1>
<div id="countdown">
<div><span id="dLeft">58</span><br />Days</div>
<div><span id="hLeft">10</span><br />Hrs</div>
<div><span id="mLeft">14</span><br />Mins</div>
<div><span id="sLeft">48</span><br />Secs</div>
</div>
<p>Celebrate the nation's birthday at <em>Tulsa's Summer
Party</em>, a daylong extravaganza in downtown
Tulsa on the 4th of July. The festivities start at 9 a.m.
with a 5K and 10K walk or race. A great event
for the whole family. Sign up as an individual or
part of a team.
</p>
<p>The <em>Farmer's
Market</em> is also back with farm-fresh produce,
meats, and dairy. There's something for every
pallet.</p>
</section>
<section>
<p>Live music starts at 11 a.m. and continues through the day
with special appearances from <em>Falstaff
Ergo</em>, <em>Crop Circles</em>, <em>Prairie Wind</em> and
<em>James Po</em>.
</p>
<p>At 9 p.m. enjoy the <em>fireworks</em> that have won awards
as the best in the Midwest, designed and presented by
<em>Wizard Works</em>. Arrive early for the best seats!
</p>
<p>After the show, dance the night away to the music of
the <em>Chromotones</em>.
</p>
<p>See you on the 4th!</p>
</section>
<nav class="vertical">
<h1>Party Links</h1>
<ul>
<li>5K and 10K Run</li>
<li>Famer's Market</li>
<li>Wizard Works</li>
<li>Falstaff Ergo</li>
<li>Crop Circles</li>
<li>James Po</li>
<li>Tulsa Fireworks</li>
<li>Prairie Wind</li>
</ul>
</nav>
</article>
<footer>
<address>
Tulsa Summer Party ·
340 Main Street, Tulsa, OK 74102 ·
(918) 555-3481
</address>
</footer>
</body>
</html>
Screenshot of my page: http://prntscr.com/isp2hu
Ive been googling and looking at possible issues and nothing has solved my problem so far.
EDIT: Added my CSS
#charset "utf-8";
#font-face {
font-family: Segment14;
src: url('segment14.woff') format('woff'),
url('segment14.ttf') format('truetype');
}
/*
New Perspectives on HTML5 and CSS3, 7th Edition
Tutorial 9
Review Assignment
Tulsa's Summer Party Layout Style Sheet
Filename: tny_layout.css
Segment14 font designed by Paul Flo Williams. Download at:
http://www.1001fonts.com/segment14-font.html#styles
*/
/* HTML and Body styles */
html {
background: linear-gradient(to bottom, rgb(120, 84, 23), rgb(51, 51, 51));
font-family: Verdana, Geneva, sans-serif;
min-height: 100%;
}
body {
margin: 0px auto;
min-width: 340px;
max-width: 1020px;
width: 100%;
min-height: 100%;
}
/* Header styles */
header img#logoImg {
display: block;
width: 100%;
}
header {
background: linear-gradient(to bottom, black 70%, rgb(185, 0, 102));
border-bottom: 1px solid rgb(0, 0, 0);
color: white;
position: relative;
width: 100%;
}
header > h1 {
position: absolute;
top: 15px;
right: 10px;
text-align: right;
font-size: 1.3em;
letter-spacing: 0.05em;
line-height: 1em;
font-family: 'Times New Roman', serif;
font-weight: normal;
color: rgba(255, 0, 192, 0.7);
}
header > h2 {
position: absolute;
top: 15px;
left: 10px;
font-size: 0.9em;
font-weight: normal;
color: rgba(255, 82, 192, 0.8);
}
/* Navigation list styles */
header nav.horizontal {
position: absolute;
bottom: 0px;
left: 0px;
width: 100%;
-webkit-flex: 0 1;
flex: 0 1;
}
body header nav ul {
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row nowrap;
flex-flow: row nowrap;
}
nav.horizontal ul li {
-webkit-flex: 1 1;
flex: 1 1;
font-size: 0.8em;
line-height: 1.5em;
height: 1.5em;
font-family: 'Trebuchet MS', Helvetica, sans-serif;
text-shadow: black 2px 1px 0px, black 4px 2px 5px;
}
nav.horizontal ul li a {
background-color: rgba(255, 255, 255, 0.2);
display: block;
color: rgba(255, 255, 255, 0.8);
text-align: center;
}
nav.horizontal ul li a:hover {
background-color: rgba(255, 88, 192, 0.5);
}
/* Time Clock Styles */
div#currentTime {
display: block;
position: absolute;
top: 35px;
left: 10px;
background-color: transparent;
border: hidden;
color: rgba(255, 82, 192, 0.8);
width: 140px;
font-size: 0.6em;
line-height: 1.1em;
font-family: 'Trebuchet MS', Helvetica, sans-serif;
font-weight: normal;
}
div#currentTime span {
display: block;
width: 100%;
}
/* Styles for the Countdown Clock */
div#countdown {
width: 100%;
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row nowrap;
flex-flow: row nowrap;
margin-top: 10px;
}
div#countdown div {
display: block;
text-align: center;
width: 100%;
line-height: 1.5em;
font-size: 0.5em;
font-family: segment14, sans-serif;
color: white;
background: rgba(51, 51, 51, 0.7);
margin: 0px 1px;
padding: 5px;
color: white;
}
div#countdown div span {
font-size: 2em;
}
/* Article Styles */
article {
background: white;
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row wrap;
flex-flow: row wrap;
}
article section, article nav.vertical {
-webkit-flex: 1 1 300px;
flex: 1 1 300px;
}
section h1 {
font-size: 1.2em;
text-align: center;
margin: 10px;
}
section p {
margin: 20px;
}
/*Section 1 styles */
article section:nth-of-type(1) {
background-color: rgba(255, 0, 192, 0.6);
}
/* Section 2 styles */
article section:nth-of-type(2) {
background-color: rgba(255, 0, 192, 0.5);
}
/* Vertical navigation list styles */
nav.vertical {
background-color: rgba(255, 0, 192, 0.7);
}
nav.vertical h1 {
color: rgba(255, 255, 255, 0.7);
text-shadow: rgba(192, 0, 145, 0.8) 2px 2px 5px;
font-size: 1.35em;
letter-spacing: 3px;
text-align: center;
padding: 10px;
margin: 0px 0px 15px 0px;
background-color: rgba(233, 0, 177, 0.5);
}
nav.vertical ul li {
font-size: 0.82em;
letter-spacing: 3px;
text-align: center;
}
nav.vertical ul li a {
display: block;
padding-left: 30px;
height: 32px;
line-height: 32px;
width: auto;
color: rgb(51, 51, 51);
}
nav.vertical ul li a:hover {
background-color: rgba(255, 192, 0, 0.45);
}
/* Page footer styles */
footer {
clear: left;
display: block;
}
footer address {
display: block;
font-style: normal;
text-align: center;
font-size: 0.5em;
line-height: 20px;
height: 20px;
background-color: rgb(215, 0, 152);
color: white;
}
/* =============================================
Tablet and Desktop Styles: greater than 510px
=============================================
*/
#media only screen and (min-width:511px) {
header > h1 {
font-size: 1.9em;
}
header > h2 {
font-size: 1.1em;
}
div#currentTime {
font-size: 0.9em;
line-height: 1em;
}
div#countdown {
font-size: 1.3em;
}
footer address {
font-size: 0.6em;
}
}
/* =============================================
Tablet and Desktop Styles: greater than 640px
=============================================
*/
#media only screen and (min-width:641px) {
header > h1 {
font-size: 2.4em;
}
header > h2 {
font-size: 1.3em;
}
nav.horizontal ul li {
font-size: 1em;
}
div#currentTime {
font-size: 1em;
line-height: 1.1em;
top: 40px;
}
div#countdown {
font-size: 1.5em;
}
footer address {
font-size: 0.8em;
}
}
/* =============================================
Tablet and Desktop Styles: greater than 720px
=============================================
*/
#media only screen and (min-width: 721px) {
header > h1 {
font-size: 3.3em;
}
header > h2 {
font-size: 1.5em;
}
div#currentTime {
font-size: 1.1em;
line-height: 1.2em;
top: 40px;
}
div#countdown {
font-size: 1.7em;
}
}
/* =============================================
Tablet and Desktop Styles: greater than 1020px
=============================================
*/
#media only screen and (min-width: 1021px) {
body {
margin: 40px auto;
}
}
You could do something as simple as this:
HTML:
<div id="minutes"></div>
<div id="seconds"></div>
JavaScript:
// set minutes
var mins = 5;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.innerHTML = getminutes();
seconds.innerHTML = getseconds();
}
secs--;
setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
countdown();
I replaced your functions with my own functions.
To update the countdown / current time/date every seconds, I set an interval that executes the function every second:
setInterval(function() { ... }, 1000); // 1000 milliseconds = 1 second
Your way of gettings the date's hours, minutes, etc. is
// Function to display current date / time on the site
setInterval(function displayTimeAndDate() {
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
var date = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
// Place 0 before the numbers if the are lower than 10
hours = (hours < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
var amOrPm;
// Check if it's a.m or p.m
if (hours < 12) {
amOrPm = "a.m";
} else {
amOrPm = "p.m";
}
document.getElementById('currentTime').innerText = month + "/" + date + "/" + year + " " + hours + ":" + minutes + ":" + seconds + " " + amOrPm;
}, 1000);
setInterval(function countdown() {
// Set the desired date (American date format: Month/Day/Year) to countdown to and the current date
var endDate = new Date('07/04/2018 09:00 PM');
var currentDate = new Date();
// Get the "distance" between the dates
var distance = endDate - currentDate;
// Initialize days, hours, minutes and seconds
var oneSecond = 1000; // 1000 milliseconds = 1 second
var oneMinute = oneSecond * 60;
var oneHour = oneMinute * 60;
var oneDay = oneHour * 24;
// Get distance in days, hours, minutes and seconds
var days = Math.floor(distance / oneDay);
var hours = Math.floor((distance % oneDay) / oneHour);
var minutes = Math.floor((distance % oneHour) / oneMinute);
var seconds = Math.floor((distance % oneMinute) / oneSecond);
// Place 0 before the numbers if the are lower than 10
hours = (hours < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
document.getElementById('countdown').innerText = days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds"
}, 1000);
<head>
<!--
New Perspectives on HTML5 and CSS3, 7th Edition
Tutorial 9
Review Assignment
Tulsa's Summer Party
Author:
Date:
Filename: tny_july.html
-->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Tulsa's Summer Party</title>
<link href="tny_base.css" rel="stylesheet" />
<link href="tny_layout.css" rel="stylesheet" />
<script src="tny_timer.js" defer></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<header>
<nav class="horizontal">
<ul>
<li>News</li>
<li>Night Beat</li>
<li>Tulsa Times</li>
<li>Calendar</li>
<li>City Links</li>
</ul>
</nav>
<img src="tny_banner2.png" id="logoImg" alt="" />
<h1>Tulsa's<br />Summer Party</h1>
<h2 id="timeHeading">Welcome to Tulsa</h2>
<div id="currentTime"></div>
</header>
<article>
<section>
<h1>Countdown to the Fireworks</h1>
<div id="countdown"></div>
<p>Celebrate the nation's birthday at <em>Tulsa's Summer
Party</em>, a daylong extravaganza in downtown Tulsa on the 4th of July. The festivities start at 9 a.m. with a 5K and 10K walk or race. A great event for the whole family. Sign up as an individual or part of a team.
</p>
<p>The <em>Farmer's
Market</em> is also back with farm-fresh produce, meats, and dairy. There's something for every pallet.
</p>
</section>
<section>
<p>Live music starts at 11 a.m. and continues through the day with special appearances from <em>Falstaff
Ergo</em>, <em>Crop Circles</em>, <em>Prairie Wind</em> and
<em>James Po</em>.
</p>
<p>At 9 p.m. enjoy the <em>fireworks</em> that have won awards as the best in the Midwest, designed and presented by
<em>Wizard Works</em>. Arrive early for the best seats!
</p>
<p>After the show, dance the night away to the music of the <em>Chromotones</em>.
</p>
<p>See you on the 4th!</p>
</section>
<nav class="vertical">
<h1>Party Links</h1>
<ul>
<li>5K and 10K Run</li>
<li>Famer's Market</li>
<li>Wizard Works</li>
<li>Falstaff Ergo</li>
<li>Crop Circles</li>
<li>James Po</li>
<li>Tulsa Fireworks</li>
<li>Prairie Wind</li>
</ul>
</nav>
</article>
<footer>
<address>
Tulsa Summer Party ·
340 Main Street, Tulsa, OK 74102 ·
(918) 555-3481
</address>
</footer>
</body>
Edit:
This time I didn't modify the HTML:
(I put it in a executable code snippet, otherwise I wouldn't be able to format it properly.)
// Function to display current date / time on the site
setInterval(function displayTimeAndDate() {
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
var date = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var amOrPm;
// Check if it's a.m or p.m
if (hours < 12) {
amOrPm = "a.m";
} else {
amOrPm = "p.m";
}
document.getElementById('date').innerText = date + ":" + month + ":" + year;
document.getElementById('time').innerText = hours + ":" + minutes + ":" + seconds + " " + amOrPm;
}, 1000);
setInterval(function countdown() {
// Set the desired date (American date format: Month/Day/Year) to countdown to and the current date
var endDate = new Date('07/04/2018 09:00 PM');
var currentDate = new Date();
// Get the "distance" between the dates
var distance = endDate - currentDate;
// Initialize days, hours, minutes and seconds
var oneSecond = 1000; // 1000 milliseconds = 1 second
var oneMinute = oneSecond * 60;
var oneHour = oneMinute * 60;
var oneDay = oneHour * 24;
// Get distance in days, hours, minutes and seconds
var days = Math.floor(distance / oneDay);
var hours = Math.floor((distance % oneDay) / oneHour);
var minutes = Math.floor((distance % oneHour) / oneMinute);
var seconds = Math.floor((distance % oneMinute) / oneSecond);
// Place 0 before the numbers if the are lower than 10
hours = (hours < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
document.getElementById('dLeft').innerText = days;
document.getElmentById('hLeft').innerText = hours;
document.getElementById('mLeft').innerText = minutes;
document.getElementById('sLeft').innerText = seconds;
}, 1000);
Take a look at FlipClock.js
The html...
<html>
<head>
<link rel="stylesheet" href="/assets/css/flipclock.css">
</head>
<body>
<div class="your-clock"></div>
<script src="/assets/js/libs/jquery.js"></script>
<script src="/assets/js/flipclock/flipclock.min.js"></script>
</body>
</html>
Instantiating in JQuery...
var clock = $('.your-clock').FlipClock({
// ... your options here
});
Instantiating in JavaScript...
var clock = new FlipClock($('.your-clock'), {
// ... your options here
});