이벤트를 지정하는 방법에 대해서 알아보자
<body> <!-- 방법 1 --> <button onclick = "alert('hello')";>hello</button> <!-- 방법 2 : 함수를 지정 --> <button onclick = "sayHello()";>hello2</button> <script> function sayHello(){ alert("hello") } </script> <!-- 방법 3 : id를 지정--> <button id ="helloBtn">hello3</button> <script> // /addEventListener는 특정이벤트 ('click')이 발생하면 sayHello 함수를 실행한다. document.getElementById('helloBtn').addEventListener('click', sayHello); document.getElementById('helloBtn').addEventListener('click', () => { alert('hello') }) </script> <!-- 방법 4 --> <button id ="helloBtn2">hello4</button> <script> const el = document.getElementById('helloBtn2') el.onclick = sayHello; </script> </body>
이벤트를 지정하는 방법에는 위와 같은 다양한 방법이 있다.
addEventListenr
에서만 작동하는 이벤트들이 있으므로addEventListener
를 사용하는 것을 권장한다!
더블클릭 실행시 발생하는 이벤트
<button id ="helloBtn">hello3</button> <script> document.getElementById('helloBtn').addEventListener('dblclick', () => { alert('hello') }) </script>
키를 누를 때(keydown)와 키를 뗄 때(keyup)발생하는 이벤트
<input id ="key"> <script> document.getElementById('key').addEventListener('keyup', (event) => { // 이벤트 콘솔 출력 console.log(event); }) </script>
인풋 박스에 키를 입력하면 발생하는 이벤트이다.
발생한 이벤트 정보를 알기 콘솔에서 확인 할 수 있다.
키가 하나 입력될 때마다 이벤트가 발생하므로 총 글자수 만큼 콘솔에 출력이 된 것을 확인 할 수 있다.
keyboradEvent
내부에서 입력 된 이벤트의 상세 정보를 확인 할 수 있다.
focus
는 인풋 박스가 포커스를 얻으면 발생하는 이벤트이다.
blur
는 인풋 박스가 포커스를 잃으면 발생하는 이벤트이다.
<input id ="focus"> <script> const input = document.getElementById('focus'); input.addEventListener('focus', (event) => { input.style.backgroundColor = 'pink' }); input.addEventListener('blur', (event) => { input.style.backgroundColor = null }); </script>
포커스를 얻으면 배경색이 바뀐다.
포커스가 인풋 박스를 벗어나서 스타일이 초기화 되었다.
마우스가 이동할 때마다 발생하는 이벤트
<div id = 'box' style="width: 100px; height: 100px; border: solid red "></div> </div> <script> const box = document.getElementById('box'); box.addEventListener('mousemove', (event) => { console.log(event) }); </script>
박스 내부에서 마우스가 움직일 때마다 콘솔에 마우스의 이벤트가 출력된다.
clientX
, clientY
속성으로 마우스의 위치를 알 수 있다.
윈도우가 가지고 있는 이벤트로 창 크기를 업데이트 해주는 이벤트.
<script> window.addEventListener('resize', () => { document.body.innerHTML = `현재 창의 크기는 ${window.innerWidth}, ${window.innerHeight} 입니다.`; }) </script>