티스토리 뷰

자바스크립트로 카운트다운 이벤트 구현하기

 

HTML

<div class="count_wrap">
	<ul id="countdown">
		<li>
			<strong id="days"></strong>
			<span>DAYS</span>
		</li>
		<li>
			<strong id="hours"></strong>
			<span>HRS</span>
		</li>
		<li>
			<strong id="minutes"></strong>
			<span>MINS</span>
		</li>
		<li>
			<strong id="seconds"></strong>
			<span>SECS</span>
		</li>
	</ul>
</div>

 

CSS

.count_wrap ul{
    display: flex;
    justify-content: center;
    align-items: center;
}
.count_wrap ul li{
    position: relative;
    text-align: center;
}
.count_wrap ul li + li{
    margin-left: 40px;
    padding-left: 40px;
}
.count_wrap ul li + li:before,
.count_wrap ul li + li:after{
    display: block;
    content: '';
    position: absolute;
    top: 20px;
    left: -4px;
    width: 8px;
    height: 8px;
    background-color: #999;
}
.count_wrap ul li + li:after{
    top: 50px;
}
.count_wrap ul li strong{
    display: block;
    font-size: 82px;
    line-height: 1em;
    font-weight: 700;
    color: #000;
    font-family:'KoPub Dotum';
}
.count_wrap ul li span{
    display: block;
    margin-top: 10px;
    font-size: 24px;
    color: #999;
}

 

javaScript

// countdown
function countDown(){
	const second = 1000,
		minute = second * 60,
		hour = minute * 60,
		day = hour * 24;
	
	const txtDay = document.getElementById('days'),
		txtHour = document.getElementById('hours'),
		txtMin = document.getElementById('minutes'),
		txtSec = document.getElementById('seconds'),
		count = document.getElementById('countdown');

	x = setInterval(function(){
		const targetDay = Date.parse('2025/01/01 00:00:00'),
			today = new Date(),
			distance = targetDay - today;
		txtDay.innerText = leadingZero(Math.floor(distance / (day))),
		txtHour.innerText = leadingZero(Math.floor((distance % (day)) / (hour))),
		txtMin.innerText = leadingZero(Math.floor((distance % (hour)) / (minute))),
		txtSec.innerText = leadingZero(Math.floor((distance % (minute)) / second));

		function leadingZero(number){
			if (number < 10){
				return '0' + number;
			}else{
				return '' + number;
			}
		}

		// D-DAY event
		// if (distance < 0) {
		//	 document.getElementById("dday_text").innerText = "D-DAY";
		//	 count.style.display = "none";
		//	 clearInterval(x);
		// }
	}, 0)
}

 

 

구현한 모습

 

*참고

https://codepen.io/AllThingsSmitty/pen/JJavZN

https://sisiblog.tistory.com/342

공지사항