How do I increment a number using 0:00:00 format? - javascript

I am trying to create a time tracker in the following format; 0:00:00. The first zero represents the hour, then minutes, then seconds. Currently, I have a working function that increments the number every second. I know there is a proper way to do this with getDate() and then modifying the hours, minutes and seconds using getHours(), getMinutes() and so on. I just can't seem to get it all to work together. I've attached a working jsFiddle to show how far I've gotten.
The goal is to have it look something like ... 0:00:59 then turn into 0:01:00 and so on. Thank you.
Full example # http://jsfiddle.net/London804/628xz9x7/2/
$('#submit').click(function(){
var start = setInterval(updateDisplay, 1000), // every millisecond call updateDisplay
timer = $('#timer'),
value = parseInt($(timer).find('.value').text(), 10);
function updateDisplay(){
value++;
$(timer).find('.value').text(value);
if (value >= 60) {
$('#sec').replaceWith("min");
}
if (value >= 3600) {
$('#sec').replaceWith("hrs");
}
if (value >= 86400) {
value = 0;
console.log('stop and take a break, you have been working over 24hrs!');
}
}
$('#stop').click(function(){
clearInterval(start);
});
$('#reset').click(function(){
clearInterval(start);
value = parseInt($(timer).find('.value').text('0'));
});
});

Here is a solution that doesn't involve all the slicing and dicing of html elements. I'm using Date objects to track elapsed time in milliseconds and updating the display by extracting a substring of a standard format string provided by the Date object.
The end result will be more accurate as you are not relying on the timer to tick off seconds but are using an actual elapsed time between calls.
You still have to mess with the final output formatting but the Date object has nice functions that allow you to pull all the components you many need in terms our hours, minutes, seconds etc...
var starting_ms ;
var elapsed ;
var $timer = $('#timer .value');
var $hrs = $('#elapsedtime #hrs');
var $min = $('#elapsedtime #min');
var $sec = $('#elapsedtime #sec');
var start;
function updateDisplay() {
elapsed.setTime(Date.now() - starting_ms);
$timer.text(elapsed.toUTCString().substr(20, 5));
$hrs.text(elapsed.getUTCHours() );
$min.text(elapsed.getUTCMinutes() );
$sec.text(elapsed.getUTCSeconds() );
}
$('#submit').click(function() {
if( start )
clearInterval(start);
starting_ms = Date.now();
elapsed = new Date(0);
start = setInterval(updateDisplay, 1000); // every millisecond call updateDisplay
});
$('#stop').click(function() {
clearInterval(start);
});
$('#reset').click(function() {
clearInterval(start);
starting_ms = Date.now();
updateDisplay();
});
* {
-webkit-tap-highlight-color: transparent
}
body {
-webkit-touch-callout: none;
-webkit-text-size-adjust: none;
-webkit-user-select: none;
background-color: #E4E4E4;
background-image: linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
background-image: -webkit-linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
background-image: -ms-linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #A7A7A7), color-stop(0.51, #E4E4E4));
background-attachment: fixed;
font-family: 'HelveticaNeue-Light', 'HelveticaNeue', Helvetica, Arial, sans-serif;
font-size: 12px;
height: 100%;
margin: 0px;
padding: 0px;
text-transform: uppercase;
width: 100%
}
.app {
background: transparent url(../../img/logo.png) no-repeat center top;
position: absolute;
left: 50%;
top: 50%;
height: 50px;
width: 225px;
text-align: center;
padding: 180px 0px 0px 0px;
margin: -115px 0px 0px -112px
}
.app #login {
margin-top: 20px;
position: relative;
font-size: 18px;
text-transform: uppercase
}
.app #login:active {
color: #cbcbcb
}
#welcome {
width: 90%;
margin: 20px auto
}
#media screen and (min-aspect-ratio: 1 / 1) and (min-width: 400px) {
.app {
background-position: left center;
padding: 75px 0px 75px 170px;
margin: -90px 0px 0px -198px
}
}
h1 {
font-size: 24px;
font-weight: normal;
margin: 0px;
overflow: visible;
padding: 0px;
text-align: center
}
.event {
border-radius: 4px;
-webkit-border-radius: 4px;
color: #FFFFFF;
font-size: 12px;
margin: 0px 30px;
padding: 2px 0px
}
.event.listening {
background-color: #333333;
display: block
}
.event.received {
background-color: #4B946A;
display: none
}
#keyframes fade {
from {
opacity: 1.0
}
50% {
opacity: 0.4
}
to {
opacity: 1.0
}
}
#-webkit-keyframes fade {
from {
opacity: 1.0
}
50% {
opacity: 0.4
}
to {
opacity: 1.0
}
}
.blink {
animation: fade 3000ms infinite;
-webkit-animation: fade 3000ms infinite
}
#timer-container {
min-width: 300px;
max-width: 50%;
margin: 0 auto
}
#timer-container #timer {
text-align: center;
font-size: 20px;
color: #4887da;
font-weight: bold
}
#timer-container label {
display: block
}
#timer-container label input {
width: 98%
}
#timer-container #button-container {
text-align: center
}
#timer-container #button-container button {
-webkit-box-shadow: 0px 1px 5px 3px #9c899c;
-moz-box-shadow: 0px 1px 5px 3px #9c899c;
box-shadow: 0px 1px 5px 3px #9c899c;
width: 35%;
margin: 10px auto;
position: relative
}
#timer-container #button-container button:nth-child(2) {
width: 20%
}
/*# sourceMappingURL=styles.css.map */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="welcome">
<h2>Welcome please log in</h2>
<p>Stuff ...</p>
</div>
<div>
<fieldset id="timer-container">
<div id="timer"><span class="value">0:00</span> <span id="sec">sec</span>
</div>
<div id="button-container">
<button id="submit" type="submit">Start</button>
<button id='reset' type="reset">Reset</button>
<button id="stop" type="stop">Stop</button>
</div>
</fieldset>
<table id="elapsedtime">
<caption>Just for fun</caption>
<tr>
<td>Hrs</td><td>Min</td><td>Sec</td>
</tr>
<tr>
<td><span id="hrs"></span></td><td><span id="min"></td><td><span id="sec"></td>
</tr>
</table>
</div>

When you start the timer, save the current date-time.
var start_dt = Date.now();
When you want to update the display, start by using the following:
var current_dt = Date.now();
var elapsed_ms = current_dt - start_dt;
That gives an accurate count of the elapsed time. Repeatedly incrementing a variable as you are doing will drift.
Now, it's time to format as H:MM:SS
function format_timer(ms) {
var s = ("0" + Math.floor((ms / ( 1000)) % 60)).substr(-2);
var m = ("0" + Math.floor((ms / ( 60*1000)) % 60)).substr(-2);
var h = Math.floor((ms / (60*60*1000)) );
return h + ":" + m + ":" + s;
}

You can accomplish it with converting your seconds to dateTime format and then with simple regex:
var myDate = new Date(null, null, null, null, null, value).toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
Here is working fiddle: http://jsfiddle.net/628xz9x7/6/

if you are certain on implementing this logic by yourself, you can make some use of some basic mathematics.
function updateDisplay(){
value++;
// Example for minutes
if (value >= 60) {
secs = value % 60;
mins = (value - secs) / 60;
$(timer).find('.value').text("00:"+min+":"+secs);
//$('#sec').replaceWith("hrs");
}
}
You can add the implementation for the other fields, but what we simply do here is find how many seconds are over the minute, by using modulus and then subtract the seconds from the minutes and divide by 60 to get the amount of minutes elapsed, we can then set the labels with these new values.
One thing you may want to do is provide a formatNumber method:
function formatNumber(number) {
if (number < 10) {
return "0" + number;
}
return number;
}
What this will do is provide the formatted string for the number to update label for values under 10, a test fiddle is here, I have not implemented all functionality but its a start for you : https://jsfiddle.net/628xz9x7/14/

JS Fiddle Demo
Note that I do an iteration every millisecond instead of a second, for faster testing.
var start, value, timer = $('#timer');
$('#submit').click(function(){
value = readTime(timer.text());
start = setInterval(updateDisplay, 1); // replace 1 with 1000
});
$('#stop').click(function(){ clearInterval(start); });
$('#reset').click(function(){
clearInterval(start);
value = parseInt(timer.text(formatTime(0)));
});
function updateDisplay(){
value++;
timer.text(formatTime(value));
if (value >= 86400) {
value = 0;
console.log('stop and take a break, you have been working over 24hrs!');
}
}
function formatTime(t){
var h = ('0' + parseInt( t / 3600 ) % 24).slice(-2),
m = ('0' + parseInt( t / 60 ) % 60).slice(-2),
s = ('0' + t % 60).slice(-2);
return h+':'+m+':'+s;
}
function readTime(s){
var r = s.split(':');
return parseInt(r[0])*3600 + parseInt(r[1])*60 + parseInt(r[2]);
}

Related

Two clocks side by side

Sorry if this has been asked a million times already, i'm quite new with this so it's difficult for me to understand some of the responses. I am trying to have two analog clocks side by side, ticking away. I am not sure why this code isn't showing that.
I would like to make a simple website of multiple timezones shown on each clock, but for now they can all be the same time.
const secondHand = document.querySelector('.second-hand');
const minsHand = document.querySelector('.min-hand');
const hourHand = document.querySelector('.hour-hand');
function setDate() {
const now = new Date();
const seconds = now.getSeconds();
const secondsDegrees = ((seconds / 60) * 360) + 90;
secondHand.style.transform = `rotate(${secondsDegrees}deg)`;
const mins = now.getMinutes();
const minsDegrees = ((mins / 60) * 360) + ((seconds / 60) * 6) + 90;
minsHand.style.transform = `rotate(${minsDegrees}deg)`;
const hour = now.getHours();
const hourDegrees = ((hour / 12) * 360) + ((mins / 60) * 30) + 90;
hourHand.style.transform = `rotate(${hourDegrees}deg)`;
}
setInterval(setDate, 1000);
setDate();
html {
background: #018DED url(https://unsplash.it/1500/1000?image=881&blur=5);
background-size: cover;
font-family: 'helvetica neue';
text-align: center;
font-size: 10px;
}
body {
margin: 0;
font-size: 2rem;
display: flex;
flex: 1;
min-height: 100vh;
align-items: center;
}
.clock,
.clocktwo {
width: 30rem;
height: 30rem;
border: 20px solid white;
border-radius: 50%;
margin: 50px auto;
position: relative;
padding: 2rem;
box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.1), inset 0 0 0 3px #EFEFEF, inset 0 0 10px black, 0 0 10px rgba(0, 0, 0, 0.2);
}
.clock-face,
.clock-facetwo {
position: relative;
width: 100%;
height: 100%;
transform: translateY(-3px);
/* account for the height of the clock hands */
}
.hand,
.handtwo {
width: 50%;
height: 6px;
background: black;
position: absolute;
top: 50%;
/* transform-origin will allow us to rotate the clock hands along the x axis, so it */
transform-origin: 100%;
transform: rotate(90deg);
transition: all 0.5s;
transition-timing-function: cubic-bezier(0.1, 2.7, 0.58, 1);
}
<div class="clock">
<div class="clock-face">
<div class="hand hour-hand"></div>
<div class="hand min-hand"></div>
<div class="hand second-hand"></div>
</div>
</div>
<div class="clocktwo">
<div class="clock-facetwo">
<div class="handtwo hour-hand"></div>
<div class="handtwo min-hand"></div>
<div class="handtwo second-hand"></div>
</div>
</div>
The problem is that you have multiple (two to be exact) of each (second, min, hour) clock 'hands'. But you use querySelector which will only select the first (from top to bottom of the HTML structure) element it finds.
What you need to do, is to select all of them using e.g. querySelectorAll and then loop over them.
const secondHand = document.querySelectorAll('.second-hand');
const minsHand = document.querySelectorAll('.min-hand');
const hourHand = document.querySelectorAll('.hour-hand');
function setDate() {
const now = new Date();
const seconds = now.getSeconds();
const secondsDegrees = ((seconds / 60) * 360) + 90;
secondHand.forEach(sec => sec.style.transform = `rotate(${secondsDegrees}deg)`);
const mins = now.getMinutes();
const minsDegrees = ((mins / 60) * 360) + ((seconds / 60) * 6) + 90;
minsHand.forEach(min => min.style.transform = `rotate(${minsDegrees}deg)`);
const hour = now.getHours();
const hourDegrees = ((hour / 12) * 360) + ((mins / 60) * 30) + 90;
hourHand.forEach(hour => hour.style.transform = `rotate(${hourDegrees}deg)`);
}
setInterval(setDate, 1000);
setDate();
html {
background: #018DED url(https://unsplash.it/1500/1000?image=881&blur=5);
background-size: cover;
font-family: 'helvetica neue';
text-align: center;
font-size: 10px;
}
body {
margin: 0;
font-size: 2rem;
display: flex;
flex: 1;
min-height: 100vh;
align-items: center;
}
.clock,
.clocktwo {
width: 30rem;
height: 30rem;
border: 20px solid white;
border-radius: 50%;
margin: 50px auto;
position: relative;
padding: 2rem;
box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.1), inset 0 0 0 3px #EFEFEF, inset 0 0 10px black, 0 0 10px rgba(0, 0, 0, 0.2);
}
.clock-face,
.clock-facetwo {
position: relative;
width: 100%;
height: 100%;
transform: translateY(-3px);
/* account for the height of the clock hands */
}
.hand,
.handtwo {
width: 50%;
height: 6px;
background: black;
position: absolute;
top: 50%;
/* transform-origin will allow us to rotate the clock hands along the x axis, so it */
transform-origin: 100%;
transform: rotate(90deg);
transition: all 0.5s;
transition-timing-function: cubic-bezier(0.1, 2.7, 0.58, 1);
}
<div class="clock">
<div class="clock-face">
<div class="hand hour-hand"></div>
<div class="hand min-hand"></div>
<div class="hand second-hand"></div>
</div>
</div>
<div class="clocktwo">
<div class="clock-facetwo">
<div class="handtwo hour-hand"></div>
<div class="handtwo min-hand"></div>
<div class="handtwo second-hand"></div>
</div>
</div>
You need to use querySelectorAll to get reference to all elements.
Then you can set the transform values for each element like this:
const bothSecondHands = document.querySelectorAll('.second-hand');
bothSecondHands.forEach(secondHand => secondHand.style.transform = `rotate(${secondsDegrees}deg)`);

Remove elements for 10 minutes after closing it

I want to remove a newsletter element for 10 minutes after closing it. The panel should remain removed if the page is reloaded within that timespan. I was thinking of using localstorage but as far I know localstorage does not have expiration. I'm thinking of using setTimeout but not sure how to use it in this context. Also, this should be done purely with Javascript without any library. JSFiddle.
<section class="newsletter">
<div id="newsletter_container" class="newsletter_class">
<h1>
Panel Title
<button id="close_btn">
close
</button>
</h1>
<h3>Panel content
</h3>
</div>
</section>
.newsletter {
position: fixed;
bottom: 0;
}
#keyframes Slide_down {
0% {
transform: translateY(0);
}
100% {
transform: translateY(250px);
}
}
#newsletter_container {
display: block;
background-color: rgb(0, 122, 193,0.7);
width: 500px;
}
.slide_down {
animation: Slide_down 1.4s ease;
}
.newsletter_class {
display: none;
}
#close_btn {
float: right;
background-color: rgb(0, 122, 193,0.7);
border: none;
cursor: pointer;
}
#media only screen and (max-width:500px) {
#newsletter_container {
width: auto;
}
.newsletter_button {
width: 75%;
padding: 5px 5px;
margin-left: 10px;
margin-bottom: 10px;
}
}
#newsletter_container h1, h3 {
font-family: Arial, Helvetica, sans-serif;
color: white;
padding: 5px 10px;
}
#newsletter_container h1 {
font-size: 16px;
}
#newsletter_container i {
color: white;
}
#newsletter_container h3 {
font-size: 12px;
}
const newsletter = document.getElementById("newsletter_container");
const closeBtn = document.getElementById("close_btn");
closeBtn.addEventListener("click",()=>{
newsletter.classList.add("slide_down");
newsletter.addEventListener("webkitAnimationEnd",function(){
newsletter.remove();
});
});
Edit:
I've used localStorage to remove the elements after reloading, but it's not permanently removed after reloading. JSFiddle.
let removeNewsletter = localStorage.getItem('removeNewsletter');
const closeNewsLetter = () => {
newsletter.classList.add("close");
localStorage.setItem('removeNewsletter','enabled');
}
if(removeNewsletter === 'enabled'){
newsletter.style.display = "none"
newsletter.addEventListener("animationend",function(){
newsletter.remove();
});
}
closeBtn.addEventListener("click",()=>{
removeNewsletter = localStorage.getItem('removeNewsletter');
if(removeNewsletter !== 'enabled'){
newsletter.addEventListener("animationend",function(){
newsletter.remove();
});
closeNewsLetter();
}
});
var storeddate = Number(localStorage.getItem("storedate"));
if(storeddate){
let diff = (Date.now() - storeddate / 60000);
if(diff < 10){
newsletter.remove();
}
}
//localStorage.setItem('removeNewsletter',null);
Use the javascript Date.now() method to get the start time and save it in the local storage. Get another Date.now() when the page loads to compare with the stored time (if any) when the page refreshes and check if the difference is longer than 10 mins.
You can compare both like this:
var storeddate = Number(localStorage.getItem("storeddate"));
if (storeddate){
var diff = (Date.now() - storeddate) / 60000;
if (diff < 10){
newsletter.style.display = "none";
}
}
ps: the Date.now() time is in milliseconds so to get it in minutes you need to divide it by 60000

Calculating Progress Bar Status based of shopping cart total

I'm looking to properly utilize a progress bar based off a users shopping cart. The threshold for free shipping is $75 so when the cart reaches $75+ the progress bar should be 100%. If the total is less than $75 the progress bar should show how much progress until it reaches $75. I've provided my code below.
I'm utilizing jQuery in my project.
<style>
p.shipping-msg-under {
font-size: 12px;
margin: 11px 0 15px 0;
line-height: 17px;
}
p.shipping-msg-over {
font-size: 12px;
margin: 11px 0 15px 0;
line-height: 17px;
}
.shipping-container {
border: 1px solid #c2c2c2;
padding: 5px 16px 5px 16px;
margin-top: 20px;
}
.shipping-price {
font-family: 'Gotham-Medium';
}
.progress-container {
background: #e0e0e0;
border-radius: 8px;
height: 8px;
/* width: 39rem; */
padding: 0;
margin-bottom: 20px;
}
.progress {
padding: 0;
margin: 0;
background: #008157;
border-radius: 5px;
height: 100%;
text-align: center;
line-height: 30px;
transition: all 0.4s ease;
}
/* Mobile */
#media only screen and (max-width: 600px) {
.container {
margin-left: 4%;
width: 38rem;
}
p.shipping-msg-under,
p.shipping-msg-over {
margin-left: 4%;
}
}
<script>
let progressThreshold = setInterval(progressMsg, 5000);
function progressMsg() {
const shippingThreshold = 75.0;
let cartValue = $('.order-total span').text().replace('$', '');
let cartTotal = parseInt(cartValue); // changes the value to a number
let cartDifference = shippingThreshold - cartTotal;
let shippingMsgOver = $(
'<p class="shipping-msg-over">Congrats! Enjoy Free Shipping on your order!</p>'
);
let shippingMsgUnder = $(
'<p class="shipping-msg-under">You are <span class="shipping-price">$' +
cartDifference +
' </span>away from Free Shipping!</p>'
);
// Progress Bar
$('.order-summary').before(
'<div class="shipping-container"><div class="progress-container"><div class="progress"></div></div></div>'
);
// Original Progress Bar Logic
// $('.progress').css('width', (cartTotal / 100) * 135 + '%');
let progressBarFull = $('.progress');
progressBarFull.style.width = `${(cartTotal / shippingThreshold) * 100}%`
// Content
if (cartTotal >= shippingThreshold) {
$('.progress-container').before(shippingMsgOver);
} else {
$('.progress-container').before(shippingMsgUnder);
}
// Remove Progress Bar
if (cartTotal >= shippingThreshold) {
// $('.container').addClass('progress-remove');
$('.container').remove();
}
clearInterval(progressThreshold);
}
// Reload the page to refresh the shipping threshold code
$('body').on('click', '.remove', function () {
location.reload();
//progressMsg();
console.log('Page Reload');
});
You can cap the percentage at 100 by using Math.min():
progressBarFull.style.width = Math.min(((cartTotal / shippingThreshold) * 100), 100) + '%';

Making This Javascript Countdown Timer Responsive

I am currently using a modified version of a JS countdown element for a site coming up. I've been learning a ton of how to use flex grids but haven't done a lot with block/inline-block, etc.
Currently when the countdown hits around 945px, the 4 inline-block boxes stay as 4 columns and end up overflowing to the edge of the screen:
My desired result would be at around 945px, the 4 columns would collapse to 2 side by side, with the text still being under their proper boxes. I was messing around altering the code in "inspect" in chrome and accidentally succeeded in doing this, but the 4 lines of text were still below the element with the boxes rather than in their proper place. Here is what my desired result looks like:
Here is the code:
https://codepen.io/Lancewalker/pen/QxpbZx
$(function (){
function countdown() {
var now = new Date();
var eventDate = new Date(2019, 0, 1);
var currentTime = now.getTime();
var evenTime = eventDate.getTime();
var remTime = evenTime - currentTime;
var sec = Math.floor(remTime / 1000);
var min = Math.floor(sec / 60);
var hur = Math.floor(min / 60);
var day = Math.floor(hur / 24);
hur %= 24;
min %= 60;
sec %= 60;
hur = (hur < 10) ? "0" + hur : hur;
min = (min < 10) ? "0" + min : min;
sec = (sec < 10) ? "0" + sec : sec;
$('.seconds').text(sec);
$('.minutes').text(min);
$('.hours').text(hur);
$('.days').text(day);
setTimeout(countdown, 1000);
}
countdown();
});
body {
background-color: #333;
}
.container {
width: 800px;
height: 350px;
margin: auto;
text-align: center
}
.container h2 {
color: #fff;
font-size: 30px;
font-family: Exo, Arial, Sans-serif;
padding: 50px 0 20px;
font-weight: normal
}
.container .content {
width: 100%;
}
.container .content > div {
display: inline-block;
margin: 35px 10px 0;
width: 120px;
height: 130px;
background: rgb(146, 163, 191, .6);
border-radius: 8px;
border: 1px solid #fff;
color: #fff;
line-height: 138px;
font-family: Exo, arial, sans-serif;
font-size: 55px;
}
.container .title {
width: ;
height: 50px;
position: relative
}
.container .title span {
display: inline-block;
width: 140px;
font-size: 20px;
font-family: 'Exo', arial, sans-serif;
color: #fff;
line-height: 50px;
}
<div class="container">
<h2>Apartments Coming Soon!</h2>
<div class="content">
<div class="days">85</div>
<div class="hours">22</div>
<div class="minutes">33</div>
<div class="seconds">54</div>
</div>
<div class="title">
<span>Days</span>
<span>Hours</span>
<span>Minutes</span>
<span>Seconds</span>
</div>
</div>
You have your .container class width set as a hard 800px value for starters.
.container {
max-width: 800px;
width: 90%;
height: 350px;
margin: auto;
text-align: center
}
Making this simple change will have your timer squares start to collapse underneath. You will have to make some more changes yourself but I would look into media queries and responsive design with %. Anytime you hard code a number such as 800px you will run into issues when you get to a smaller size.
I would also consider refactoring your HTML so that the time squares and titles are together.
<div class="time-square">
<div class="time-square-time">88</div>
<div class="time-square-title">Days</div>
</div>
You will be able to move your HTML around a little more cleanly this way, you are going to run into a few issues matching the title to the time in your current structure
I would suggest restructuring your markup slightly - wrapping the number and the text ('day', 'hour', etc) in the same parent. This will ensure they stay together when content is wrapped.
For the CSS, change width: 800px to max-width - this ensure the content resizes on screens smaller than 800px.
You can then use CSS Grid to layout the boxes and simplify the code.
Codepen
$(function() {
function countdown() {
var now = new Date();
var eventDate = new Date(2019, 0, 1);
var currentTime = now.getTime();
var evenTime = eventDate.getTime();
var remTime = evenTime - currentTime;
var sec = Math.floor(remTime / 1000);
var min = Math.floor(sec / 60);
var hur = Math.floor(min / 60);
var day = Math.floor(hur / 24);
hur %= 24;
min %= 60;
sec %= 60;
hur = (hur < 10) ? "0" + hur : hur;
min = (min < 10) ? "0" + min : min;
sec = (sec < 10) ? "0" + sec : sec;
$('.seconds').text(sec);
$('.minutes').text(min);
$('.hours').text(hur);
$('.days').text(day);
setTimeout(countdown, 1000);
}
countdown();
});
body {
background: #333;
}
.container {
max-width: 800px;
height: 350px;
margin: auto;
text-align: center;
}
.container h2 {
color: #fff;
font-size: 30px;
font-family: Exo, Arial, Sans-serif;
padding: 50px 0 20px;
font-weight: normal;
}
.content {
display: grid;
grid-template-columns: repeat(auto-fit, 120px);
/* use grid gap instead of margin around boxes */
grid-gap: 10px;
justify-content: center;
}
.box>div {
height: 130px;
background: rgb(146, 163, 191, 0.6);
border-radius: 8px;
border: 1px solid #fff;
color: #fff;
font-family: Exo, arial, sans-serif;
font-size: 55px;
margin-bottom: 20px;
/* use flexbox instead of lineheight for vertical centering */
display: flex;
align-items: center;
justify-content: center;
}
.box span {
display: inline-block;
font-size: 20px;
font-family: "Exo", arial, sans-serif;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h2>Apartments Coming Soon!</h2>
<div class="content">
<div class="box">
<div class="days">85</div>
<span>Days</span>
</div>
<div class="box">
<div class="hours">22</div>
<span>Hours</span>
</div>
<div class="box">
<div class="minutes">33</div>
<span>Minutes</span>
</div>
<div class="box">
<div class="seconds">54</div>
<span>Seconds</span>
</div>
</div>
</div>
Just split into to two parts of div, it will looks fine.
If I misunderstood your question, please let me know.
$(function (){
function countdown() {
var now = new Date();
var eventDate = new Date(2019, 0, 1);
var currentTime = now.getTime();
var evenTime = eventDate.getTime();
var remTime = evenTime - currentTime;
var sec = Math.floor(remTime / 1000);
var min = Math.floor(sec / 60);
var hur = Math.floor(min / 60);
var day = Math.floor(hur / 24);
hur %= 24;
min %= 60;
sec %= 60;
hur = (hur < 10) ? "0" + hur : hur;
min = (min < 10) ? "0" + min : min;
sec = (sec < 10) ? "0" + sec : sec;
$('.seconds').text(sec);
$('.minutes').text(min);
$('.hours').text(hur);
$('.days').text(day);
setTimeout(countdown, 1000);
}
countdown();
});
body {
background-color: #333;
}
.container {
width: 800px;
height: 350px;
margin: auto;
text-align: center
}
.container h2 {
color: #fff;
font-size: 30px;
font-family: Exo, Arial, Sans-serif;
padding: 50px 0 20px;
font-weight: normal
}
.container .content {
width: 100%;
}
.container .content > div {
display: inline-block;
margin: 35px 10px 0;
width: 120px;
height: 130px;
background: rgb(146, 163, 191, .6);
border-radius: 8px;
border: 1px solid #fff;
color: #fff;
line-height: 138px;
font-family: Exo, arial, sans-serif;
font-size: 55px;
}
.container .title {
width: ;
height: 50px;
position: relative
}
.container .title span {
display: inline-block;
width: 140px;
font-size: 20px;
font-family: 'Exo', arial, sans-serif;
color: #fff;
line-height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h2>Apartments Coming Soon!</h2>
<div class="content">
<div class="days">85</div>
<div class="hours">22</div>
</div>
<div class="title">
<span>Days</span>
<span>Hours</span>
</div>
<div class="content">
<div class="minutes">33</div>
<div class="seconds">54</div>
</div>
<div class="title">
<span>Minutes</span>
<span>Seconds</span>
</div>
</div>
You can use CSS Media Queries like following:
#media (max-width: 992px) {
.container .content > div, .container .title span {
width: 20%;
}
}
#media (max-width: 768px) {
.container .content > div, .container .title span {
width: 50%;
}
}

crossfade effect not working properly

i copied this code from codepen.io to add a crossfade effect to my site's background images.
var bgImageArray = ["lonely.jpg", "uluwatu.jpg", "carezza-lake.jpg", "batu-bolong-temple.jpg"],
base = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/full-",
secs = 4;
bgImageArray.forEach(function(img){
new Image().src = base + img;
// caches images, avoiding white flash between background replacements
});
function backgroundSequence() {
window.clearTimeout();
var k = 0;
for (i = 0; i < bgImageArray.length; i++) {
setTimeout(function(){
document.documentElement.style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center fixed";
document.documentElement.style.backgroundSize ="cover";
if ((k + 1) === bgImageArray.length) { setTimeout(function() { backgroundSequence() }, (secs * 1000))} else { k++; }
}, (secs * 1000) * i)
}
}
backgroundSequence();
* {
box-sizing: border-box;
}
html {
margin: 0;
background-size: cover;
background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/full-lonely.jpg") no-repeat center center fixed;
background-blend-mode: darken;
// blend mode optional at this stage; will be used more in the next demo.
transition: 3s;
}
body { margin: 0; }
div#texttop {
color: #fff;
width: 30%;
margin-top: 5%;
margin-left: 5%;
padding: 2rem;
border: 4px double rgba(255,255,255,0.3);
background: rgba(0,0,0,0.3);
font-family: Oxygen, sans-serif;
h1 {
margin-top: 0;
text-align: center;
font-weight: 100;
}
p {
line-height: 1.6;
}
}
#media all and (max-width: 770px) {
div#texttop { display: none; }
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="texttop">
<h1>True Cross-Fade Background Images</h1>
<p>A repeating sequence of fullscreen background images, pushed all the way to the root element. Crossfading effect in Webkit-derived browsers (Chrome, Safari, Opera).</p>
</div>
the images are cycling fine, but they aren't doing the cross fading transition, they're just changing without the crossfade effect. and occasionally there are white flashes between the image cycle.
i've inserted a snippet of the code here, and it still isn't working. perhaps there's something missing that i can't find?
codepen.io is using scss you should copy the compiled css,
var bgImageArray = ["lonely.jpg", "uluwatu.jpg", "carezza-lake.jpg", "batu-bolong-temple.jpg"],
base = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/full-",
secs = 4;
bgImageArray.forEach(function(img){
new Image().src = base + img;
// caches images, avoiding white flash between background replacements
});
function backgroundSequence() {
window.clearTimeout();
var k = 0;
for (i = 0; i < bgImageArray.length; i++) {
setTimeout(function(){
document.documentElement.style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center fixed";
document.documentElement.style.backgroundSize ="cover";
if ((k + 1) === bgImageArray.length) { setTimeout(function() { backgroundSequence() }, (secs * 1000))} else { k++; }
}, (secs * 1000) * i)
}
}
backgroundSequence();
* {
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
html {
margin: 0;
background-size: cover;
background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/full-lonely.jpg") no-repeat center center fixed;
background-blend-mode: darken;
-webkit-transition: 3s;
transition: 3s;
}
body {
margin: 0;
}
div#texttop {
color: #fff;
width: 30%;
margin-top: 5%;
margin-left: 5%;
padding: 2rem;
border: 4px double rgba(255, 255, 255, 0.3);
background: rgba(0, 0, 0, 0.3);
font-family: Oxygen, sans-serif;
}
div#texttop h1 {
margin-top: 0;
text-align: center;
font-weight: 100;
}
div#texttop p {
line-height: 1.6;
}
#media all and (max-width: 770px) {
div#texttop {
display: none;
}
}
<div id="texttop">
<h1>True Cross-Fade Background Images</h1>
<p>A repeating sequence of fullscreen background images, pushed all the way to the root element. Crossfading effect in Webkit-derived browsers (Chrome, Safari, Opera).</p>
</div>

Categories