퍼블리싱/Javascript
toDolist(javascript)
리리히히
2021. 10. 19. 22:35
반응형
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.delete {
display: none;
}
</style>
</head>
<body>
<div class="container">
<h1>TO DO LIST</h1>
<div>
<input id="userInput" type="text" placeholder="New item..." maxlength="27">
<button id="enterBtn">enter</button>
</div>
<!-- 리스트 등록영역 -->
<div class="listItems">
<ul>
</ul>
</div>
</div>
<script>
var enterBtn = document.getElementById("enterBtn");
var inputBox = document.getElementById("userInput");
var ul = document.querySelector("ul");
var item = document.getElementsByTagName("li");
function inputLength() {
return inputBox.value.length;
}
function listLength() {
return item.length;
}
function createListElement() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(inputBox.value)); //input영역 안에
ul.appendChild(li); //ul 태그 안에 li 태그 추가
inputBox.value = ""; //텍스트 input 영역을 초기화
//새로운 item들을 추가
function crossOut() {
li.classList.toggle("done"); //toggle 클래스 유무체크 -> add/remove 자동실행
}
li.addEventListener("click", crossOut);
var dBtn = document.createElement("button");
dBtn.appendChild(document.createTextNode("X"));
li.appendChild(dBtn);
dBtn.addEventListener("click", deleteListItem);
//class delete 추가 (display : none)
function deleteListItem() {
li.classList.add("delete")
}
}
function addListAfterClick() {
if (inputLength() > 0) {
createListElement();
}
}
function addListAfterKeypress(event) {
if (inputLength() > 0 && event.which === 13) {
createListElement();
}
}
//함수호출
enterBtn.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);
// target.addEventListener(type, listener[, options])
//
// type: 반응할 이벤트 유형을 나타내는 대소문자 구분 문자열
//
// listener: 지정된 type의 이벤트가 발생했을 때, 알림받는 객체(function 객체여야 함)
//
// https: //developer.mozilla.org/ko/docs/Web/API/EventTarget/addEventListener#the_event_listener_callback
</script>
</body>
</html>
반응형