D-day Counter -1단계
<!DOCTYPE html>
<html lang="en">
<head>
<title>D-day</title>
<script>
const dateFormMaker = function(){
const inputYear=document.querySelector('#target-year-input').value
const inputMonth=document.querySelector('#target-month-input').value
const inputDate=document.querySelector('#target-date-input').value
console.log(inputYear, inputMonth, inputDate)
};
</script>
</head>
<body>
<input id="target-year-input" class="target-input"/>
<input id="target-month-input" class="target-input"/>
<input id="target-date-input" class="target-input"/>
<button onclick="dateFormMaker()">버튼</button>
</body>
</html>
D-day Counter -2단계
<!DOCTYPE html>
<html lang="en">
<head>
<title>D-day</title>
<script>
const dateFormMaker = function(){
const inputYear=document.querySelector('#target-year-input').value
const inputMonth=document.querySelector('#target-month-input').value
const inputDate=document.querySelector('#target-date-input').value
const dateFormat = inputYear +'-'+ inputMonth + '-'+inputDate
console.log(dateFormat)
};
const counterMaker = function(){
const nowDate = new Date()
const targetDate = new Date(dateFormat) //dateFormMaker함수의 지역변수이므로 사용X
const remaining = (targetDate - nowDate)/1000
const remainingDate = Math.floor(remaining/3600/24);
const remainingHours = Math.floor(remaining/3600)% 24;
const remainingMin = Math.floor(remaining/60)% 60;
const remainingSec = Math.floor(remaining) % 60;
console.log(remainingDate,remainingHours,remainingMin,remainingSec)
}
</script>
</head>
<body>
<input id="target-year-input" class="target-input"/>
<input id="target-month-input" class="target-input"/>
<input id="target-date-input" class="target-input"/>
<button onclick="counterMaker()">버튼</button>
</body>
</html>
▶ 함수 안에서 선언된 변수는 지역변수이며, 함수의 영역안에 갖히게 된다.
▶ 그러나 함수 밖에서 선언된 변수는 함수 안에서도 사용될 수 있다.
▶ const dateFormat 이라는 상수변수는
▶ dateFormMaker함수 안에 갖혀 있는 지역변수이다.
▶ 이를 극복하기 위해서는 dateFormMaker를 호출하고 반환값인 dateFormat를 targetDateInput에 저장한다.
그리고 targetDateInput을 Date()함수에 매개 변수로 넣는다.
D-day Counter - 3단계
<!DOCTYPE html>
<html lang="en">
<head>
<title>D-day</title>
<script>
const dateFormMaker = function(){
const inputYear=document.querySelector('#target-year-input').value
const inputMonth=document.querySelector('#target-month-input').value
const inputDate=document.querySelector('#target-date-input').value
// const dateFormat = inputYear +'-'+ inputMonth + '-'+inputDate
const dateFormat =`${inputYear}-${inputMonth}-${inputDate}`
return dateFormat;
};
const counterMaker = function(){
const targetDateInput = dateFormMaker()
const nowDate = new Date()
const targetDate = new Date(targetDateInput).setHours(0, 0, 0, 0)//자정을 기준으로 함
const remaining = (targetDate - nowDate)/1000
const remainingDate = Math.floor(remaining/3600/24);
const remainingHours = Math.floor(remaining/3600)% 24;
const remainingMin = Math.floor(remaining/60)% 60;
const remainingSec = Math.floor(remaining) % 60;
console.log(remainingDate,remainingHours,remainingMin,remainingSec)
}
</script>
</head>
<body>
<input id="target-year-input" class="target-input"/>
<input id="target-month-input" class="target-input"/>
<input id="target-date-input" class="target-input"/>
<button onclick="counterMaker()">버튼</button>
</body>
</html>
D-day Counter - 4단계
<!DOCTYPE html>
<html lang="en">
<head>
<title>D-day</title>
<link rel="stylesheet" href="style.css" />
<script>
const dateFormMaker = function () {
const inputYear = document.querySelector("#target-year-input").value;
const inputMonth = document.querySelector("#target-month-input").value;
const inputDate = document.querySelector("#target-date-input").value;
// const dateFormat = inputYear +'-'+ inputMonth + '-'+inputDate
const dateFormat = `${inputYear}-${inputMonth}-${inputDate}`;
return dateFormat;
};
const counterMaker = function () {
const targetDateInput = dateFormMaker();
const nowDate = new Date();
const targetDate = new Date(targetDateInput).setHours(0, 0, 0, 0); //자정을 기준으로 함
const remaining = (targetDate - nowDate) / 1000;
const remainingDate = Math.floor(remaining / 3600 / 24);
const remainingHours = Math.floor(remaining / 3600) % 24;
const remainingMin = Math.floor(remaining / 60) % 60;
const remainingSec = Math.floor(remaining) % 60;
console.log(remainingDate, remainingHours, remainingMin, remainingSec);
};
</script>
</head>
<body>
<h1>D-Day</h1>
<div id="d-day-container">
<div class="d-day-child-container">
<span id="days">0</span>
<span>일</span>
</div>
<div class="d-day-child-container">
<span id="hours">0</span>
<span>시간</span>
</div>
<div class="d-day-child-container">
<span id="min">0</span>
<span>분</span>
</div>
<div class="d-day-child-container">
<span id="sec">0</span>
<span>초</span>
</div>
</div>
<div id="target-selector">
<input id="target-year-input" class="target-input" size="5" /> -
<input id="target-month-input" class="target-input" size="5" /> -
<input id="target-date-input" class="target-input" size="5" />
</div>
<button onclick="counterMaker()" id="start-btn">카운트다운 시작</button>
</body>
</html>
css
* {
box-sizing: border-box;
}
body {
display: flex;
flex-direction: column;
align-items: center;
}
h1 {
font-size: 3rem;
}
.btn {
margin-top: 0.5rem;
font-size: 1.3rem;
}
#d-day-container {
display: flex;
flex-wrap: wrap;
flex-direction: row;
justify-content: center;
margin-bottom: 1.6rem;
}
.d-day-child-container {
text-align: center;
margin-right: 1rem;
}
.d-day-child-container span {
font-size: 1.3rem;
}
D-day Counter - 5단계
<!DOCTYPE html>
<html lang="en">
<head>
<title>D-day</title>
<link rel="stylesheet" href="./style.css" />
<script>
const dateFormMaker = function () {
const inputYear = document.querySelector("#target-year-input").value;
const inputMonth = document.querySelector("#target-month-input").value;
const inputDate = document.querySelector("#target-date-input").value;
// const dateFormat = inputYear +'-'+ inputMonth + '-'+inputDate
const dateFormat = `${inputYear}-${inputMonth}-${inputDate}`;
return dateFormat;
};
const counterMaker = function () {
const targetDateInput = dateFormMaker();
const nowDate = new Date();
const targetDate = new Date(targetDateInput).setHours(0, 0, 0, 0); //자정을 기준으로 함
const remaining = (targetDate - nowDate) / 1000;
console.log(remaining);
//만약 remaining ===0이 되면, 타이머가 종료 되었습니다. 출력
if (remaining <= 0) {
console.log("타이머가 종료 되었습니다. ");
} else if (isNaN(remaining)) {
//만약 잘못된 날짜가 들어온 경우, 유효한 시간대가 아닙니다. 출력
console.log("유효한 시간대가 아닙니다.");
}
const remainingDate = Math.floor(remaining / 3600 / 24);
const remainingHours = Math.floor(remaining / 3600) % 24;
const remainingMin = Math.floor(remaining / 60) % 60;
const remainingSec = Math.floor(remaining) % 60;
};
</script>
</head>
<body>
<h1>D-Day</h1>
<div id="d-day-container">
<div class="d-day-child-container">
<span id="days">0</span>
<span>일</span>
</div>
<div class="d-day-child-container">
<span id="hours">0</span>
<span>시간</span>
</div>
<div class="d-day-child-container">
<span id="min">0</span>
<span>분</span>
</div>
<div class="d-day-child-container">
<span id="sec">0</span>
<span>초</span>
</div>
</div>
<div id="target-selector">
<input id="target-year-input" class="target-input" size="5" /> -
<input id="target-month-input" class="target-input" size="5" /> -
<input id="target-date-input" class="target-input" size="5" />
</div>
<button onclick="counterMaker()" id="start-btn">카운트다운 시작</button>
</body>
</html>
▶ isNaN(remaining)
▶ 어떠한 data가 NaN인지 아닌지 판별할 때는 '비교연산자'를 사용하지 않고,
자바스크립트에 내장되어 있는 isNaN(data)를 사용한다.
D-day Counter - 6단계
//script파일
const messageContainer = document.querySelector("#d-day-message");
messageContainer.textContent = "D-Day를 입력해 주세요.";
const dateFormMaker = function () {
const inputYear = document.querySelector("#target-year-input").value;
const inputMonth = document.querySelector("#target-month-input").value;
const inputDate = document.querySelector("#target-date-input").value;
// const dateFormat = inputYear +'-'+ inputMonth + '-'+inputDate
const dateFormat = `${inputYear}-${inputMonth}-${inputDate}`;
return dateFormat;
};
const counterMaker = function () {
const targetDateInput = dateFormMaker();
const nowDate = new Date();
const targetDate = new Date(targetDateInput).setHours(0, 0, 0, 0); //자정을 기준으로 함
const remaining = (targetDate - nowDate) / 1000;
console.log(remaining);
//만약 remaining ===0이 되면, 타이머가 종료 되었습니다. 출력
if (remaining <= 0) {
console.log("타이머가 종료 되었습니다. ");
} else if (isNaN(remaining)) {
//만약 잘못된 날짜가 들어온 경우, 유효한 시간대가 아닙니다. 출력
console.log("유효한 시간대가 아닙니다.");
}
const remainingDate = Math.floor(remaining / 3600 / 24);
const remainingHours = Math.floor(remaining / 3600) % 24;
const remainingMin = Math.floor(remaining / 60) % 60;
const remainingSec = Math.floor(remaining) % 60;
};
//textContent
const messageContainer = document.querySelector('#d-day-message')
messageContainer.textContent='안녕하세요'
element.textContent = "내용"
↑해당 태그에 직접 "텍스트를 추가시킴"
//html파일
<!DOCTYPE html>
<html lang="en">
<head>
<title>D-day</title>
<link rel="stylesheet" href="./style.css" />
<script src="./script.js" defer></script>
</head>
<body>
<h1>D-Day</h1>
<div id="d-day-container">
<div class="d-day-child-container">
<span id="days">0</span>
<span>일</span>
</div>
<div class="d-day-child-container">
<span id="hours">0</span>
<span>시간</span>
</div>
<div class="d-day-child-container">
<span id="min">0</span>
<span>분</span>
</div>
<div class="d-day-child-container">
<span id="sec">0</span>
<span>초</span>
</div>
</div>
<div id="d-day-message"></div>
<div id="target-selector">
<input id="target-year-input" class="target-input" size="5" /> -
<input id="target-month-input" class="target-input" size="5" /> -
<input id="target-date-input" class="target-input" size="5" />
</div>
<button onclick="counterMaker()" id="start-btn">카운트다운 시작</button>
</body>
</html>
D-day Counter - 7단계(별도의 객체를 만듬)
messageContainer.innerHTML = "<h3>D-Day를 입력해주세요.</h3>";
변수.innerHTML text자체에 태그를 입력해서 그 태그를 적용
//querySelector vs getElementById
const days = document.querySelector("#days");
const hours = document.querySelector("#hours");
const min = document.querySelector("#min");
const sec = document.querySelector("#sec");
const days = document.getElementById("days");
const hours = document.getElementById("hours");
const min = document.getElementById("min");
const sec = document.getElementById("sec");
const messageContainer = document.querySelector("#d-day-message");
// messageContainer.textContent = "D-Day를 입력해 주세요.";
messageContainer.innerHTML = "<h3>D-Day를 입력해주세요.</h3>";
const container = document.querySelector("#d-day-container");
// container.style.display = "none";
const dateFormMaker = function () {
const inputYear = document.querySelector("#target-year-input").value;
const inputMonth = document.querySelector("#target-month-input").value;
const inputDate = document.querySelector("#target-date-input").value;
const dateFormat = `${inputYear}-${inputMonth}-${inputDate}`;
return dateFormat;
};
const counterMaker = function () {
const targetDateInput = dateFormMaker();
const nowDate = new Date();
const targetDate = new Date(targetDateInput).setHours(0, 0, 0, 0); //자정을 기준으로 함
const remaining = (targetDate - nowDate) / 1000;
console.log(remaining);
//만약 remaining ===0이 되면, 타이머가 종료 되었습니다. 출력
if (remaining <= 0) {
messageContainer.innerHTML = "<h3>타이머가 종료 되었습니다</h3>";
} else if (isNaN(remaining)) {
//만약 잘못된 날짜가 들어온 경우, 유효한 시간대가 아닙니다. 출력
messageContainer.innerHTML = "<h3>유요한 시간대가 아닙니다.</h3>";
}
const remainingObj = {
remainingDate: Math.floor(remaining / 3600 / 24),
remainingHours: Math.floor(remaining / 3600) % 24,
remainingMin: Math.floor(remaining / 60) % 60,
remainingSec: Math.floor(remaining) % 60,
};
const documentObj = {
days: document.getElementById("days"),
hours: document.getElementById("hours"),
min: document.getElementById("min"),
sec: document.getElementById("sec"),
};
documentObj["days"].textContent = remainingObj["remainingDate"]; //태그요소.textContent
documentObj["hours"].textContent = remainingObj["remainingHours"];
documentObj["min"].textContent = remainingObj["remainingMin"];
documentObj["sec"].textContent = remainingObj["remainingSec"];
};
반복문을 이용한 코드 축약
//1단계
// documentObj["days"].textContent = remainingObj["remainingDate"];
// documentObj["hours"].textContent = remainingObj["remainingHours"];
// documentObj["min"].textContent = remainingObj["remainingMin"];
// documentObj["sec"].textContent = remainingObj["remainingSec"];
//2단계
const timeKeys = Object.keys(remainingObj);
const docKeys = Object.keys(documentObj);
for (let i = 0; i < timeKeys.length; i++) {
documentObj[docKeys[i]].textContent = remainingObj[timeKeys[i]];
}
//3단계
let i = 0;
for (let key in documentObj) {
documentObj[key].textContent = remainingObj[timeKeys[i]];
i++;
}
for ( let 임시변수 in 객체) { }
for( let k in documentObj){ }
console.log(k);
<출력결과>
days
hours
min
sec
결론: for-in반복문에서 임시변수 k는 documentObj객체의 "키"에 접근한다.
원본 데이터
const documentObj = {
days: document.getElementById("days"),
hours: document.getElementById("hours"),
min: document.getElementById("min"),
sec: document.getElementById("sec"),
};
const timeKeys = Object.keys(remainingObj);
let i = 0;
for (let key in documentObj) {
documentObj[key].textContent = remainingObj[timeKeys[i]];
i++;
}
코드를 간결하게 축약
const documentArr = ["days", "hours", "min", "sec"];
const timeKeys = Object.keys(remainingObj);
let i = 0;
for (let element of documentArr) {
// console.log(element);
document.getElementById(element).textContent = remainingObj[timeKeys[i]];
i++;
}
for( let 임시변수 of 배열) { }
for(let element of documentArr){ }
console.log(element)
<출력결과>
days
hours
min
sec
결론: for-of반복문에서 element는 "배열 요소"에 접근한다
D-day Counter - 8단계
const messageContainer = document.querySelector("#d-day-message");
messageContainer.innerHTML = "<h3>D-Day를 입력해주세요.</h3>";
const container = document.querySelector("#d-day-container");
container.style.display = "none";
const dateFormMaker = function () {
const inputYear = document.querySelector("#target-year-input").value;
const inputMonth = document.querySelector("#target-month-input").value;
const inputDate = document.querySelector("#target-date-input").value;
const dateFormat = `${inputYear}-${inputMonth}-${inputDate}`;
return dateFormat;
};
const counterMaker = function () {
const targetDateInput = dateFormMaker();
const nowDate = new Date();
const targetDate = new Date(targetDateInput).setHours(0, 0, 0, 0); //자정을 기준으로 함
const remaining = (targetDate - nowDate) / 1000;
console.log(remaining);
//만약 remaining ===0이 되면, 타이머가 종료 되었습니다. 출력
if (remaining <= 0) {
container.style.display = "none;";
messageContainer.innerHTML = "<h3>타이머가 종료 되었습니다</h3>";
messageContainer.style.display = "flex";
return;
} else if (isNaN(remaining)) {
//만약 잘못된 날짜가 들어온 경우, 유효한 시간대가 아닙니다. 출력
container.style.display = "none;";
messageContainer.innerHTML = "<h3>유요한 시간대가 아닙니다.</h3>";
messageContainer.style.display = "flex";
return;
}
const remainingObj = {
remainingDate: Math.floor(remaining / 3600 / 24),
remainingHours: Math.floor(remaining / 3600) % 24,
remainingMin: Math.floor(remaining / 60) % 60,
remainingSec: Math.floor(remaining) % 60,
};
const timeKeys = Object.keys(remainingObj);
const documentArr = ["days", "hours", "min", "sec"];
let i = 0;
for (let element of documentArr) {
// console.log(element);
document.getElementById(element).textContent = remainingObj[timeKeys[i]];
i++;
}
};
const starter = function () {
container.style.display = "flex";
messageContainer.style.display = "none";
counterMaker();
};
//html파일
countMaker()함수를 starter()함수로 변경
<button onclick="starter()" id="start-btn">카운트다운 시작</button>
D-day Counter - 9단계
const messageContainer = document.querySelector("#d-day-message");
messageContainer.innerHTML = "<h3>D-Day를 입력해주세요.</h3>";
const container = document.querySelector("#d-day-container");
container.style.display = "none";
const intervalIdArr = [];
const dateFormMaker = function () {
const inputYear = document.querySelector("#target-year-input").value;
const inputMonth = document.querySelector("#target-month-input").value;
const inputDate = document.querySelector("#target-date-input").value;
const dateFormat = `${inputYear}-${inputMonth}-${inputDate}`;
return dateFormat;
};
const counterMaker = function (data) {
const nowDate = new Date();
const targetDate = new Date(data).setHours(0, 0, 0, 0); //자정을 기준으로 함
const remaining = (targetDate - nowDate) / 1000;
console.log(remaining);
//만약 remaining ===0이 되면, 타이머가 종료 되었습니다. 출력
if (remaining <= 0) {
container.style.display = "none;";
messageContainer.innerHTML = "<h3>타이머가 종료 되었습니다</h3>";
messageContainer.style.display = "flex";
setClearInterval();
return;
} else if (isNaN(remaining)) {
//만약 잘못된 날짜가 들어온 경우, 유효한 시간대가 아닙니다. 출력
container.style.display = "none;";
messageContainer.innerHTML = "<h3>유요한 시간대가 아닙니다.</h3>";
messageContainer.style.display = "flex";
setClearInterval();
return;
}
const remainingObj = {
remainingDate: Math.floor(remaining / 3600 / 24),
remainingHours: Math.floor(remaining / 3600) % 24,
remainingMin: Math.floor(remaining / 60) % 60,
remainingSec: Math.floor(remaining) % 60,
};
const timeKeys = Object.keys(remainingObj);
const documentArr = ["days", "hours", "min", "sec"];
const format = function (time) {
if (time < 10) {
return "0" + time;
} else {
return time;
}
};
let i = 0;
for (let element of documentArr) {
const remainingTime = format(remainingObj[timeKeys[i]]); //format함수 호출
console.log(remainingTime);
document.getElementById(element).textContent = remainingTime;
i++;
}
};
const starter = function () {
const targetDateInput = dateFormMaker();
container.style.display = "flex";
messageContainer.style.display = "none";
setClearInterval();
counterMaker(targetDateInput);
const intervalId = setInterval(() => {
counterMaker(targetDateInput);
}, 1000);
intervalIdArr.push(intervalId);
};
const setClearInterval = function () {
for (let i = 0; i < intervalIdArr.length; i++) {
clearInterval(intervalIdArr[i]);//interval()함수의 id값을 삭제
}
};
const resetTimer = function () {
container.style.display = "none";
messageContainer.innerHTML = "<h3>D-Day를 입력해주세요.</h3>";
messageContainer.style.display = "flex";
setClearInterval();
};
const temp = () => { } 화살표 함수
() => { } 익명함수(화살표함수)
setTimeout(콜백함수, 시간)
setTimeout(함수이름, 시간)
예시
setTimeout(콜백함수, 5000)
→5초를 "지연"시킨 다음에 "콜백함수"가 실행됨
→Interval마다 가지고 있는 id값을 반환
setInterval(콜백함수, 시간)
const text = function() {
console.log('hi')
}
setInterval( () =>{ text() }, 1000)
→1초마다 test함수를 호출
setInterval(함수이름, 시간)
setInterval(test, 1000)
→1초마다 test함수를 호출
D-day Counter - 10단계(완성)
const messageContainer = document.querySelector("#d-day-message");
messageContainer.innerHTML = "<h3>D-Day를 입력해주세요.</h3>";
const container = document.querySelector("#d-day-container");
container.style.display = "none";
const intervalIdArr = [];
const savedDate = localStorage.getItem("saved-date");
const dateFormMaker = function () {
const inputYear = document.querySelector("#target-year-input").value;
const inputMonth = document.querySelector("#target-month-input").value;
const inputDate = document.querySelector("#target-date-input").value;
const dateFormat = `${inputYear}-${inputMonth}-${inputDate}`;
return dateFormat;
};
const counterMaker = function (data) {
if (data !== savedDate) {
//새로 입력된 데이터와 저장된 데이터가 같지 않다면
localStorage.setItem("saved-data", data);
}
const nowDate = new Date();
const targetDate = new Date(data).setHours(0, 0, 0, 0); //자정을 기준으로 함
const remaining = (targetDate - nowDate) / 1000;
//만약 remaining ===0이 되면, 타이머가 종료 되었습니다. 출력
if (remaining <= 0) {
container.style.display = "none;";
messageContainer.innerHTML = "<h3>타이머가 종료 되었습니다</h3>";
messageContainer.style.display = "flex";
setClearInterval();
return;
} else if (isNaN(remaining)) {
//만약 잘못된 날짜가 들어온 경우, 유효한 시간대가 아닙니다. 출력
container.style.display = "none;";
messageContainer.innerHTML = "<h3>유요한 시간대가 아닙니다.</h3>";
messageContainer.style.display = "flex";
setClearInterval();
return;
}
const remainingObj = {
remainingDate: Math.floor(remaining / 3600 / 24),
remainingHours: Math.floor(remaining / 3600) % 24,
remainingMin: Math.floor(remaining / 60) % 60,
remainingSec: Math.floor(remaining) % 60,
};
const timeKeys = Object.keys(remainingObj);
const documentArr = ["days", "hours", "min", "sec"];
const format = function (time) {
if (time < 10) {
return "0" + time;
} else {
return time;
}
};
let i = 0;
for (let element of documentArr) {
const remainingTime = format(remainingObj[timeKeys[i]]); //format함수 호출
console.log(remainingTime);
document.getElementById(element).textContent = remainingTime;
i++;
}
};
const starter = function (targetDateInput) {
if (!targetDateInput) {
//애당초 saved-Data이 없다면
targetDateInput = dateFormMaker();
}
container.style.display = "flex";
messageContainer.style.display = "none";
setClearInterval();
counterMaker(targetDateInput);
const intervalId = setInterval(() => {
counterMaker(targetDateInput);
}, 1000);
intervalIdArr.push(intervalId);
};
const setClearInterval = function () {
localStorage.removeItem("saved-data"); //타이머를 초기화하는 경우 localStorage에 저장된 데이터 삭제
for (let i = 0; i < intervalIdArr.length; i++) {
clearInterval(intervalIdArr[i]);
}
};
const resetTimer = function () {
container.style.display = "none";
messageContainer.innerHTML = "<h3>D-Day를 입력해주세요.</h3>";
messageContainer.style.display = "flex";
setClearInterval();
};
if (savedDate) {
//savedDate가 존재한다면
starter(savedDate);
} else {
container.style.display = "none";
messageContainer.innerHTML = "<h3>D-Day를 입력해주세요.</h3>";
}
▶ localStorage.setItem( '키', value) → '키'는 String타입이다.
▶ localStorage.removeItem('키')
'훈훈한 javascript' 카테고리의 다른 글
TodoList (0) | 2023.01.11 |
---|---|
함수 선언의 종류 (0) | 2023.01.09 |
훈훈한 javascript 요약 (0) | 2023.01.09 |
querySelector★★ (0) | 2023.01.09 |