반응형
Hold Shift and Check 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>
<!--
The following is a common layout you would see in an email client.
When a user clicks a checkbox, holds Shift, and then clicks another checkbox a few rows down, all the checkboxes inbetween those two checkboxes should be checked.
-->
<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>
목표
shift키로 체크박스를 동시에 체크 할 수 있는 기능을 추가하는 것
과정
- 함수 작성에 필요한 변수, 상수 작성
- 함수 생성
- 함수 호출
코드 분석
1. 함수작성에 필요한 변수, 상수 작성
const checkboxes = document.querySelectorAll('.inbox input[type="checkbox"]');
let lastChecked;
checkboxes
에 inbox
클래스 하위의 체크박스 요소들을 담고 빈 변수 lastChecked
를 선언
2. 함수 생성
const 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;
}
inBetween
에 false를 할당해놓고 만약 쉬프트키를 누르고, 누른것이 체크가 되어있다면 조건문을 실행
처음 버튼을 누를 때 쉬프트를 누르고 클릭하면 하위의 모든 내용 체크,
두번째 버튼을 쉬프트 누르고 클릭하면 사이의 모든 내용 체크하는 내용을 3중 조건문으로 표현.
3. 함수 호출
checkboxes.forEach(checkbox => checkbox.addEventListener('click', handleCheck));
체크박스를 클릭시 위에 작성한 함수를 호출