개발/JavaScript 30
10. Hold Shift and Checkboxes
Sangminnn
2017. 4. 14. 23:55
반응형
코드 분석
<!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
값을 가지게 되고 그에 따라 모두 체크가 된다고 해석이 가능하다.
마무리
코드는 많지 않았지만 이어지는 조건문의 해석이 어려웠다.
끝.
반응형