Event
※ 코드 독해시 어려움 있을경우 console.dir(event) 을 통해 각 파라미터 혹은 하위 카테고리 확인해보기
※ Event Driven Programming (이벤트 기반 프로그래밍) : 이벤트의 발생에 의해 프로그램 흐름이 결정되는 프로그래밍 패러다임
1) Event 사용
① 문서객체.addEventListener('이벤트명', 콜백함수)
② 문서객체.removeEventListener('이벤트명', 콜백함수)
2) 키보드 이벤트
① keydown : 키가 눌릴 때 실행
② keypress : 키가 입력되었을 때 실행
③ keyup : 눌렀던 키를 떨어질 때 실행
// 키보드 입력 시 글자 수 출력 //
<body>
<h3>글자 수 : 0</h3>
<input type="text" name="title" id="title">
</body>
<script>
const h3 = document.querySelector('h3');
const input = document.querySelector('input');
input.addEventListener('keypress', function (event) {
const length = input.value.length;
h3.textContent = `글자 수 : ${length + 1}`;
});
</script>
3) 드롭다운(Select) 목록 활용
<body>
<select>
<option>떡볶이</option>
<option>순대</option>
<option>오뎅</option>
<option>튀김</option>
</select>
<p>선택: 떡볶이</p>
</body>
<script>
const select = document.querySelector('select');
const p = document.querySelector('p');
select.addEventListener('change', (event) => {
const options = event.currentTarget.options;
const index = event.currentTarget.options.selectedIndex;
p.textContent = `선택: ${options[index].textContent}`
});
</script>
4) 체크박스 활용 // input[type="checkbox"]
<body>
<input type="checkbox">
<span>타이머 활성화</span>
<h1></h1>
</body>
<script>
let [timer, timerId] = [0, 0];
const h1 = document.querySelector('h1');
const checkbox = document.querySelector('input');
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
timerId = setInterval(() => {
timer += 1;
h1.textContent = `${timer}초`;
}, 1000);
} else {
clearInterval(timerId);
}
});
</script>
5) 라디오버튼 활용 // input[type="radio"]
<body>
<h3># 좋아하는 동물을 선택해주세요</h3>
<input type="radio" name="pet" value="강아지"><span>강아지</span>
<input type="radio" name="pet" value="고양이"><span>고양이</span>
<input type="radio" name="pet" value="햄스터"><span>햄스터</span>
<input type="radio" name="pet" value="기타"><span>기타</span>
<hr>
<h3 id="output"></h3>
</body>
<script>
const output = document.querySelector('#output');
const radios = document.querySelectorAll('[name=pet]');
radios.forEach((radio) => {
radio.addEventListener('change', (event) => {
const current = event.currentTarget;
if (current.checked) {
output.textContent = `선택된 동물은 ${current.value}`;
}
});
});
</script>
6) 기본 이벤트 비활성화 기능 // preventDefault()
<body>
<img src="http://placekitten.com/300/300" alt="">
<img src="http://placekitten.com/300/300" alt="">
<a href="http://www.google.com">google</a>
</body>
<script>
const imgs = document.querySelectorAll('img')
imgs.forEach((img) => {
img.addEventListener('contextmenu', (event) => {
event.preventDefault();
});
});
const a = document.querySelectorAll('a')
a.forEach((a) => {
a.addEventListener('click', (event) => {
event.preventDefault();
});
a.addEventListener('contextmenu', (event) => {
event.preventDefault();
});
});
</script>
7) 이벤트 전달 비활성화 기능 // stopPropagation()
<body>
<style>
div {
border: 1px solid blue;
display: inline-block;
}
div>div {
width: 50px;
height: 50px;
margin: 20px;
}
</style>
<div style='width: 200px; height: 200px;'>
<div style='background-color: red;'></div>
<div style='background-color: blue; border-radius: 25px;'></div>
</div>
<script>
document.querySelector('div > div:first-child').addEventListener('click', (event) => {
console.log('red div');
event.stopPropagation();
});
document.querySelector('div > div:last-child').addEventListener('click', (event) => {
console.log('blue div');
event.stopPropagation();
});
document.querySelector('body > div').addEventListener('click', (event) => {
console.log('parent div');
});
</script>