Languages/JS

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

Dev다D 2021. 2. 19. 12:13
반응형

효율적으로 완료한 일 체크하기!

 

  1. 이벤트 위임을 활용할 수 있도록 이벤트 핸들러, updateToDo 함수를 완성해 주세요. updateToDo는 이벤트가 발생한 대상이 item이라는 클래스 속성 값을 가지고 있을 때 동작해야 합니다.
  2. 이벤트 핸들러를 li 태그 각각에 등록하는 것이 아니라 하나의 태그에만 등록해 주세요.

코드를 잘 작성했다면,

  1. 첫 번째 두 번째 할 일 뿐만아니라 자바스크립트로 추가한 네 번째 할 일을 클릭했을 때도 'done'이라는 class 속성값이 toggle되면서 스타일 변해야 합니다.
  2. 세 번째 할 일은 클릭을 해도 아무런 변화가 없어야 합니다.

 


<!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">
        <li class="item">자바스크립트 공부하기</li>
        <li class="item">고양이 화장실 청소하기</li>
        <li class="item">고양이 장난감 쇼핑하기</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');

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

toDoList.addEventListener('click', updateToDo);


// 테스트 코드
const newToDo = document.createElement('li');
newToDo.textContent = '가계부 정리하기';
newToDo.classList.add('item');
toDoList.append(newToDo);

toDoList.children[2].addEventListener('click', function(e) {e.stopPropagation()});

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

 

반응형