Countdown till the end of the year - JS - javascript

I'm working on a countdown in JS that going to count every second down to the end of 2016, at the end of 2016 I'll display a message to the user.
My issue is that I'm off by one hour from the actual time
I used this website(https://www.timeanddate.com/counters/newyear.html) to see if my countdown is displaying the correct time.
Here is my Code:
function updateTimer(deadline){
// going to give us the new date and time when this function was called which is every second.
// also getting back the date and time of the instance of updateTimer was called.
// time = deadline the point we're counting too - time of the function was called. (in milliseconds)
// the object is going to work out based on the time difference.
// Math Floor always round DOWN.
// time / 1000 = 1000 converted to seconds, 60 converted min,60 is hours, 24 is days
// time / 1000 = 1000 converted to seconds, 60 converted min,60 is hours % 24 == how many hours left in the particular day. 100 % 24 = 4 hours
var time = deadline - new Date();
return{
'days': Math.floor( time/(1000*60*60*24) ),
'hours': Math.floor( (time/(1000*60*60)) % 24),
'minutes': Math.floor( (time/1000/60) %60 ),
'seconds': Math.floor( (time/1000) %60 ),
'total': time
};
}
function animateClock(span){
span.className = "turn"; // giving a class turn into the injected span.
setTimeout(function(){
span.className = "";
},700);
}
// SetInterval going to be fired every second.
function startTimer(id,deadline){
var timerInterval = setInterval(function(){
var clock = document.getElementById(id); //getting the match id from the DOM.
var timer = updateTimer(deadline); // generating a function and injecting it a deadline.
// ref to the HTML with div clock - concat the series of spans
clock.innerHTML = '<span>' + timer.days + '</span>'
+'<span>' + timer.hours + '</span>'
+'<span>' + timer.minutes + '</span>'
+'<span>' + timer.seconds + '</span>';
// Animations
var spans = clock.getElementsByTagName("span"); // will get all the above spans that been injected to the clock div.
animateClock(spans[3]); // calling this function every second.
if(timer.seconds == 59) animateClock(spans[2]); // == 59 because we're going to be in a second 60 which is a minute.
if(timer.minutes == 59 && timer.seconds == 59) animateClock(spans[1]);
if(timer.hours == 23 && timer.minutes == 59 && timer.seconds == 59) animateClock(spans[0]); // when we getting to a new day.
// Check for the end of timer.
if(timer.total < 1){ //means the difference
clearInterval(timerInterval);
clock.innerHTML ='<span>0</span><span>0</span><span>0</span><span>0</span>';
}
},1000);
}
// when the window loads fire this function.
window.onload = function(){
var deadline = new Date("January 1, 2017 23:59:59"); // Declare a deadline.
startTimer("clock",deadline); // we're going to inject into the clock id of the html the deadline.
};
body{
background: #282e3a;
font-family: Tahoma;
}
h1{
color:#fff;
text-align: center;
font-size:74px;
letter-spacing: 10px;
}
#del-countdown{
width:850px;
margin: 15% auto;
}
#clock span{
float: left;
text-align: center;
font-size: 84px;
margin: 0 2.5%;
color:#fff;
padding: 20px;
width:20%;
border-radius: 20px;
box-sizing: border-box;
}
#clock span:nth-child(1){
background: #DA3B36;
}
#clock span:nth-child(2){
background: #2e6da4;
}
#clock span:nth-child(3){
background: #f6bc58;
}
#clock span:nth-child(4){
background: #5CB85C;
}
#clock:after{
content: "";
display: block;
clear: both;
}
#units span{
float: left;
width:25%;
text-align: center;
margin-top: 30px;
color:#ddd;
text-transform: uppercase;
font-size: 13px;
letter-spacing: 2px;
text-shadow: 1px 1px 1px 1px rgba(10,10,10,0.7);
}
span.turn{
animation: turn 0.5s ease forwards;
}
#keyframes turn{
0%{transform: rotatex(0deg)}
100%{transform: rotatex(360deg)}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Countdown</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="del-countdown">
<h1>COUNTDOWN</h1>
<div id="clock"></div>
<div id="units">
<span>Days</span>
<span>Hours</span>
<span>Minutes</span>
<span>Seconds</span>
</div>
</div>
<script src="countdown.js"></script>
</body>
</html>

Your deadline should be:
var deadline = new Date("January 1, 2017 00:00:00")

Related

Countdown is stopping when user is out of current tab

I create a simple countdown with a "invert" progress bar - to control session in my website.
when time is over, page will be reload and without the session - blocked.
ISSUE:
The progress bar works fine - but IF the user change the window or the current tab - and "forgot" the page open - the countdown stops. I don't know why
THE CODE:
function progress(timeleft, timetotal, $element) {
var progressBarWidth = timeleft * $element.width() / timetotal;
$element.find('div').animate({ width: progressBarWidth }, timeleft == timetotal ? 0 : 1000, "linear");
if(timeleft > 0) {
setTimeout(function() {
progress(timeleft - 1, timetotal, $element);
}, 1000);
}
};
progress(30, 30, $('#progressBar'));
#progressBar {
width: 90%;
margin: 10px auto;
height: 2px;
background-color: #E0E0E0;
}
#progressBar div {
height: 100%;
text-align: right;
padding: 0 0px;
line-height: 2px;
width: 0;
background-color: #FF0000;
box-sizing: border-box;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="progressBar">
<div class="bar"></div>
</div>
JSFIDDLE: https://jsfiddle.net/2tonbd5k
Any idea to solve this?
I'm think I need to change the fixed "timeleft or timetotal" (+3Min) to a "real time" (user access the site at 21:57:00 then the "real time" to reload will be +3 minutes - 22:00:00 PM). If user go out, the animation will stop too - but when he returns the js will correct to the real time. I can update the "time" with ASP - but how I can do this?
** for test purposes timeleft in code is only 30s.
all you need is add this script
if ( document.hidden ) { return; }
the result is here
https://jsfiddle.net/mfkLea7w/

countdown timer is not working while creating coming soon page

I am trying to display a countdown timer for coming soon webpage. Everything is working fine except for the timer that is written in javascript. I also tried by making it an external file. It also reads the file when making external but the timer is not shown on the page.
This is my blade file
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title> Coming Soon</title>
<link rel="stylesheet" type="text/css" href="{{asset('css/style.css')}}">
<link href="https://fonts.googleapis.com/css2?family=Balsamiq+Sans:ital#1&family=Montserrat&family=Open+Sans+Condensed:wght#300&family=Playfair+Display&display=swap" rel="stylesheet">
</head>
<body>
<header>
<div class="soon">
<p> We will be back with beautiful website</p>
<h1>COMING SOON</h1>
<hr>
<p id="launch"></p>
</header>
<script>
var date = new Date("Jan 1, 2020 00:00:00").getTime();
var countdownfunction = setInterval(function() {
var today = new Date().getTime();
var distance = date - today;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (distance < 0) {
clearInterval(countdownfunction);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
</body>
</html>
And this is css
*
{
margin: 0;
padding: 0;
}
header
{
background-image: linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5)),url('/images/comingsoon.jpg');
height: 100vh;
background-position: center;
background-size: cover;
}
.soon {
top: 50%;
left: 50%;
position: absolute;
transform:translate(-50%,-50%);
color: #fff;
text-align: center;
font-family: 'Balsamiq Sans', cursive;
font-family: 'Montserrat', sans-serif;
font-family: 'Open Sans Condensed', sans-serif;
font-family: 'Playfair Display', serif;
}
h1 {
font-size: 60px;
letter-spacing: 15px;
}
hr{
width: 50%;
margin: 30px auto;
border: 1.5px solid #fff;
}
p{
font-size:20px;
margin-bottom:30px;
}
you have to add a tag with id demo like a div
and also your future date is wrong
<header>
<div class="soon">
<p> We will be back with beautiful website</p>
<h1>COMING SOON</h1>
<hr>
<div id=demo></div>div>
<p id="launch"></p>
</header>
your date is expired change it to something in the future
var date = new Date("Jan 1, 2021 00:00:00").getTime();
change <p id="launch"></p> to <p id="demo"></p> on html code,
or change document.getElementById("demo") to document.getElementById("launch") on script code

time shown is blank for javascript application

can someone take a look at this and tell me what I'm doing wrong?
I wanted to use these other techniques just as an exercise.
such as using element id / using a separate js file to recreate a clock application that shows the current date. However, it keeps showing up as blank:
"use strict";
var $ = function(id) { return document.getElementById(id); };
var padSingleDigit = function(num) {
return (num < 10) ? "0" + num : num;
};
// callback function for displaying clock time
var displayTime = function(now) {
$("hours").firstChild.nodeValue = now.hours;
$("minutes").firstChild.nodeValue = padSingleDigit(now.minutes);
$("seconds").firstChild.nodeValue = padSingleDigit(now.seconds);
$("ampm").firstChild.nodeValue = now.ampm;
// display date in "m/d/yyyy" format - correct for zero-based month
var date = (now.getMonth() + 1) + "/" + now.getDate() + "/" + now.getFullYear();
$("date").firstChild.nodeValue = date;
};
// onload event handler
window.onload = function() {
var clock = createClock(displayTime);
// start clock
clock.start();
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
color: blue;
}
label {
float: left;
width: 11em;
text-align: right;
padding-bottom: .5em;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
fieldset {
margin-bottom: 1em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Clock</title>
<link rel="stylesheet" href="clock.css">
<script src="clock.js"></script>
</head>
<body>
<main>
<h1>Digital clock</h1>
<fieldset>
<legend>Clock</legend>
<span id="date"> </span>:
<span id="minutes"> </span>:
<span id="seconds"> </span>
<span id="ampm"> </span>
</fieldset>
</main>
</body>
</html>
The problem is you are referencing an element that does not exist. There is no element with the id of "hours" in your code.

Background Width jQuery Specification Not Working

I created a web page where the background of my page changes depending on the hour. I want the background image to always be the full width of the page, so I am trying to set it to be 100%, but it doesn't seem to be working. Is there some part of the code that's written incorrectly? Do I need to implement something else?
body {
margin-left: 5%;
margin-right: 5%;
}
#demo {
color: white;
}
#txt {
color: white;
float: left;
font-family: OpenSans;
font-size: 90px;
margin: 20px;
}
#weather {
color: white;
float: right;
font-family: OpenSans;
font-size: 40px;
margin: 20px;
}
<!DOCTYPE html>
<html>
<head>
<title>Blooming Time And Temperature</title>
<link href="css/format.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script>
function startTime() {
document.getElementById('txt').innerHTML =
moment().format("hh:mm A");
var t = setTimeout(startTime, 1000);
var hour = moment().hour()
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
function changeBackground(){
var hour = new Date().getHours();
if(hour > 7 && hour <= 12)
{
// It's morning
$('body').css('background', 'url(sequence/1.jpg) no-repeat').width('100%');
}
else if(hour > 12 && hour < 18)
{
// It's noon
$('body').css('background', 'url(sequence/2.jpg) no-repeat').width('100%');
}
else if(hour > 19 && hour < 21)
{
// It's noon
$('body').css('background', 'url(sequence/3.jpg) no-repeat').width('100%');
}
else
{
// It's night
$('body').css('background', 'url(sequence/4.jpg) no-repeat').width('100%');
}
}
changeBackground(); // invoke for the first time manually
setInterval(changeBackground, 1000 * 60 * 60);
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.simpleWeather/3.1.0/jquery.simpleWeather.min.js"></script>
<script>
$(document).ready(function() {
$.simpleWeather({
location: 'Brooklyn, NY',
woeid: '',
unit: 'f',
success: function(weather) {
html = '<p>'+weather.temp+'°'+weather.units.temp+'</p>';
html += '<div id="city">'+weather.city+', '+weather.region+'</div>';
$("#weather").html(html);
},
error: function(error) {
$("#weather").html('<p>'+error+'</p>');
}
});
});
</script>
</head>
<body onload="startTime()"">
<div id="txt"></div>
<div id="weather"></div>
</body>
</html>
You could try removing the margin attributes on the body tag in your CSS, and set background-size: cover on the body tag there. Then in your changeBackground function, you mightn't need the .width(100%); method, since the width shouldn't change when you swap out the background images?
If you are putting the background image on the body and you have this css property, it won't do.
body {
margin-left: 5%;
margin-right: 5%;
}
Make the property
body {
margin:0;
}

Background Image jQuery Isn't Working, What Am I Doing Wrong?

I am trying to create a site that has a background image that changes every hour. I want the background image to correspond with a certain time of day. For example, an image of closed flower bud would be the site background at 12AM and an image of a blooming flower bud would be the site background at 12PM.
I am pretty sure the way I am currently implementing this is the correct way, and on inspection I don't get any errors, but the background images are not showing up. What am I doing wrong? Is it the way I'm using the jQuery or another aspect of my code? Any help is greatly appreciated. Thanks in advance.
body {
margin-left: 5%;
margin-right: 5%;
}
#demo {
color: white;
}
#txt {
color: white;
float: left;
font-family: OpenSans;
font-size: 90px;
margin: 20px;
}
#weather {
color: white;
float: right;
font-family: OpenSans;
font-size: 40px;
margin: 20px;
}
<!DOCTYPE html>
<html>
<head>
<title>Blooming Time And Temperature</title>
<link href="css/format.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script>
function startTime() {
document.getElementById('txt').innerHTML =
moment().format("hh:mm A");
var t = setTimeout(startTime, 1000);
var hour = moment().hour()
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
setInterval(function(){
var hour = new Date().getHours();
if(hour > 7 && hour <= 12)
{
// It's morning
$('body').css('background', 'url(http://www.magic4walls.com/wp-content/uploads/2015/11/Macro-of-water-droplets-on-pink-lotus-flower-blooming-in-early-morning.jpg) no-repeat');
}
else if(hour > 12 && hour < 18)
{
// It's noon
$('body').css('background', 'url(http://www.magic4walls.com/wp-content/uploads/2015/11/Macro-of-water-droplets-on-pink-lotus-flower-blooming-in-early-morning.jpg) no-repeat');
}
else
{
// It's night
$('body').css('background', 'url(http://www.magic4walls.com/wp-content/uploads/2015/11/Macro-of-water-droplets-on-pink-lotus-flower-blooming-in-early-morning.jpg) no-repeat');
}
}, 1000 * 60 *60);
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.simpleWeather/3.1.0/jquery.simpleWeather.min.js"></script>
<script>
$(document).ready(function() {
$.simpleWeather({
location: 'Brooklyn, NY',
woeid: '',
unit: 'f',
success: function(weather) {
html = '<p>'+weather.temp+'°'+weather.units.temp+'</p>';
html += '<div id="city">'+weather.city+', '+weather.region+'</div>';
$("#weather").html(html);
},
error: function(error) {
$("#weather").html('<p>'+error+'</p>');
}
});
});
</script>
</head>
<body onload="startTime()"">
<div id="txt"></div>
<div id="weather"></div>
</body>
</html>
Function that is provided to setInterval method will be invoked for the first time after time you provided (which is one hour). Change it to:
function changeBackground(){
var hour = new Date().getHours();
if(hour > 7 && hour <= 12)
{
// It's morning
$('body').css('background', 'url(http://www.magic4walls.com/wp-content/uploads/2015/11/Macro-of-water-droplets-on-pink-lotus-flower-blooming-in-early-morning.jpg) no-repeat');
}
else if(hour > 12 && hour < 18)
{
// It's noon
$('body').css('background', 'url(http://www.magic4walls.com/wp-content/uploads/2015/11/Macro-of-water-droplets-on-pink-lotus-flower-blooming-in-early-morning.jpg) no-repeat');
}
else
{
// It's night
$('body').css('background', 'url(http://www.magic4walls.com/wp-content/uploads/2015/11/Macro-of-water-droplets-on-pink-lotus-flower-blooming-in-early-morning.jpg) no-repeat');
}
}
changeBackground(); // invoke for the first time manually
setInterval(changeBackground, 1000 * 60 * 60);

Categories