Created
August 5, 2020 10:03
-
-
Save MACscr/bad4a447ba37c787d79f14a5df1e11fe to your computer and use it in GitHub Desktop.
Home Assistant Countdown Card
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CountdownToDateCard extends HTMLElement { | |
constructor() { | |
super(); | |
this.attachShadow({ | |
mode: 'open' | |
}); | |
} | |
setConfig(config) { | |
if (!config.target_date) { | |
throw new Error('You need to define an target_date'); | |
} | |
const root = this.shadowRoot; | |
if (root.lastChild) root.removeChild(root.lastChild); | |
const card = document.createElement('ha-card'); | |
const content = document.createElement('div'); | |
card.id = 'ha-card'; | |
content.id = 'content'; | |
card.appendChild(content); | |
root.appendChild(card); | |
this._config = config; | |
} | |
set hass(hass) { | |
// dont update | |
if (this.ran) { | |
return; | |
} | |
this.ran = true; | |
const root = this.shadowRoot; | |
const config = this._config; | |
const card = root.getElementById("ha-card"); | |
const content = root.getElementById("content"); | |
card.header = config.title ? config.title : 'Countdown Timer'; | |
// Set the date we're counting down to | |
var countDownDate = new Date(config.target_date).getTime(); | |
// Update the count down every 1 second | |
var x = setInterval(function() { | |
// Get today's date and time | |
var now = new Date().getTime(); | |
// Find the distance between now and the count down date | |
var distance = countDownDate - now; | |
// Time calculations for days, hours, minutes and seconds | |
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); | |
content.innerHTML = days + "d " + hours + "h " | |
+ minutes + "m " + seconds + "s "; | |
// If the count down is finished, write some text | |
if (distance < 0) { | |
clearInterval(x); | |
content.innerHTML = "It's Time!"; | |
} | |
}, 1000); | |
} | |
getCardSize() { | |
return 1; | |
} | |
} | |
customElements.define('countdown-to-date-card', CountdownToDateCard); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
style: | | |
#content { | |
text-align: center; | |
font-size: 40px; | |
padding: 20px; | |
} | |
target_date: 'Jul 18, 2020 17:00:00' | |
title: Family Reunion! | |
type: 'custom:countdown-to-date-card' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment