Languages/JS

[인터랙티브 Javascript] 03. 이벤트 살펴보기

Dev다D 2021. 2. 19. 10:50
반응형

완료한 일 체크하기!

 

  1. 이벤트 객체를 활용한 이벤트 핸들러, updateToDo 함수를 완성해 주세요. 이 함수는 이벤트가 발생한 대상에 'done'이라는 class 속성값을 toggle하는 함수여야 합니다.
  2. 반복되는 부분들이 좀 더 간단하게 정리되도록 이벤트 핸들러를 등록하는 반복문을 작성해 주세요.

코드를 잘 작성했다면, 첫 번째 두 번째 할 일은 클릭했을 때 'done'이라는 class 속성값이 toggle되면서 스타일이 변하고, 세 번째 할 일은 클릭을 해도 아무런 변화가 없어야 합니다.


<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>오늘 할 일</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main">
    <h2 class="title">오늘 할 일</h2>
    <ul id="to-do-list" class="to-do-list">
        <li>자바스크립트 공부하기</li>
        <li>고양이 화장실 청소하기</li>
        <li>고양이 장난감 쇼핑하기</li>
    </ul>
</div>
<script src="index.js"></script>
</body>
</html>
body {
    margin: 0;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}

.main {
    width: 350px;
    margin: 40px;
    padding: 30px 0;
    background-color: #FCFCFC;
    box-shadow: -5px -5px 20px #DFDFDF,  5px 5px 20px #BABECC;
    border-radius: 8px;
    text-align: center;
}

.title {
    margin: 15px auto;
    font-size: 30px;
    font-weight: 600;
    color: #9600FF;
}

#to-do-list {
    width: 280px;
    margin: 0 auto 15px;
    padding: 0;
    list-style: none;
}

#to-do-list li {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 90%;
    height: 40px;
    margin: 8px auto 15px;
    border-bottom: 1px solid #9600FF;
    cursor: pointer;
}

.done {
    opacity: 0.5;
    text-decoration: line-through;
}
const toDoList = document.querySelector('#to-do-list');
const items = toDoList.children;

function updateToDo(event) {
    event.target.classList.toggle('done');
}

for (let i = 0; i < items.length; i++) {
    items[i].addEventListener('click', updateToDo)
}


// 테스트 코드
items[2].removeEventListener('click', updateToDo);

본 내용은 Codeit의  'Javascript 중급' 강의를
참고하여 작성한 내용입니다.

 

반응형