본문 바로가기

개발/JavaScript 30

10. Hold Shift and Checkboxes

반응형

코드 분석

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Hold Shift to Check Multiple Checkboxes</title>
</head>
<body>
  <style>

    html {
      font-family: sans-serif;
      background:#ffc600;
    }

    .inbox {
      max-width:400px;
      margin:50px auto;
      background:white;
      border-radius:5px;
      box-shadow:10px 10px 0 rgba(0,0,0,0.1);
    }

    .item {
      display:flex;
      align-items:center;
      border-bottom: 1px solid #F1F1F1;
    }

    .item:last-child {
      border-bottom:0;
    }


    input:checked + p {
      background:#F9F9F9;
      text-decoration: line-through;
    }

    input[type="checkbox"] {
      margin:20px;
    }

    p {
      margin:0;
      padding:20px;
      transition:background 0.2s;
      flex:1;
      font-family:'helvetica neue';
      font-size: 20px;
      font-weight: 200;
      border-left: 1px solid #D1E2FF;
    }


  </style>

  <div class="inbox">
    <div class="item">
      <input type="checkbox">
      <p>This is an inbox layout.</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Check one item</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Hold down your Shift key</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Check a lower item</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Everything inbetween should also be set to checked</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Try do it with out any libraries</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Just regular JavaScript</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Good Luck!</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Don't forget to tweet your result!</p>
    </div>
  </div>
    <script>

    </script>
</body>
</html>

목표

박스 체크를 할 수 있는 삼중 조건문을 알아보자.

분석

const checkboxes = document.querySelectorAll('.inbox input[type="checkbox"]');

let lastChecked;

function handleCheck(e) {
  let inBetween = false;
  if (e.shiftKey && this.checked) {
    checkboxes.forEach(checkbox => {
      console.log(checkbox);
      if (checkbox === this || checkbox === lastChecked) {
        inBetween = !inBetween;
        console.log('STarting to check them inbetween!');
      }
      if (inBetween) {
        checkbox.checked = true;
      }

    });
  }

  lastChecked = this;
}

checkboxes.forEach(checkbox => checkbox.addEventListener('click', handleCheck));

handleCheck라는 함수의 선언으로 먼저 inBetween false값으로 둔 다음, 쉬프트키를 누르고 체크를 하면 아래의 조건문이 나오는데 그 안에 조건문이 더 있다.
이걸 이해하는 과정에서 가장 어려웠던 것은 checkbox === this 이다. 원래 this에 대한 이해가 부족했던 탓이다.
이를 계기로 this 에 대해 조금 더 찾아보았는데, 여기서의 this는 아무래도 check 를 말하는 것 같다.

그래서 결국 정리를 해보면!

체크를 하거나, 마지막에 체크가 되면 inBetween = !inBetween을 실행하여 처음 클릭한 박스와 마지막으로 클릭한 박스 사이의 inBetween값을 false에서 true로 변환하고, 그 아래의 조건문에 따라 true inBetween값을 가진 부분은 모두 체크가 되도록 하는 방식이다.

이것은 또한, 처음 시점을 정하지 않고 바로 쉬프트 + 클릭으로 시점을 정한 경우에는 클릭한 박스부터 맨 아래의 내용까지는 모두 inBetween true값을 가지게 되고 그에 따라 모두 체크가 된다고 해석이 가능하다.

마무리

코드는 많지 않았지만 이어지는 조건문의 해석이 어려웠다.

끝.

반응형

'개발 > JavaScript 30' 카테고리의 다른 글

12. Key Sequence Detection  (0) 2017.04.18
11. Custom Video Player  (0) 2017.04.18
9. Dev Tools Domination  (0) 2017.04.13
8. Fun with HTML5 Canvas  (0) 2017.04.12
7. Array Cardio Day 2  (2) 2017.04.11