🧨

11. 이벤트

  • 클릭 이벤트 CODE
<!DOCTYPE html> <html> <head> <title>Document</title> </head> <body> <button id="click_btn" type="button">클릭해주세요!</button> <script> var click_btn = document.getElementById('click_btn'); click_btn.addEventListener('click', click_event); //클릭 이벤트 function click_event(){ alert('클릭 이벤트 발생!'); } /* 이벤트 종류 onchange : HTML의 요소 값을 변경할 경우 사용하는 이벤트 onclick : 사용자가 마우스를 눌렀다 뗀 경우 발생하는 이벤트 onblur : 요소가 포커스를 잃었을 경우 발생하는 이벤트 onmouseover : 마우스를 요소 위로 움직일 때 사용하는 이벤트 onmouseout : 마우스를 요소 밖으로 움직일 때 사용하는 이벤트 onkeydown : 키보드의 키를 누른 경우 발생하는 이벤트 onload : 브라우저에서 페이지의 로딩이 끝났을 경우 발생하는 이벤트 */ </script> </body> </html>
 

이벤트 종류

  • onchange : HTML의 요소 값을 변경할 경우 사용하는 이벤트
  • onclick : 사용자가 마우스를 눌렀다 뗀 경우 발생하는 이벤트
  • onblur : 요소가 포커스를 잃었을 경우 발생하는 이벤트
  • onmouseover : 마우스를 요소 위로 움직일 때 사용하는 이벤트
  • onmouseout : 마우스를 요소 밖으로 움직일 때 사용하는 이벤트
  • onkeydown : 키보드의 키를 누른 경우 발생하는 이벤트
  • onkeydown : 키보드의 키를 누른 경우 발생하는 이벤트
  • onload : 브라우저에서 페이지의 로딩이 끝났을 경우 발생하는 이벤트
 
  • blur 이벤트 CODE
<!DOCTYPE html> <html> <head> <title>Document</title> </head> <body> <form action="index.html" method="post"> <label id="text_id">아이디</label> <input id="user_id" type="text" /> <label id="text_pw">비밀번호</label> <input id="user_pw" type="password" /> <div id="msg"> </div> </form> <script> var user_pw = document.getElementById('user_pw'); user_pw.addEventListener('blur', blur_event); //비밀번호가 6글자 미만일 경우 메시지 출력 function blur_event(){ var msg = document.getElementById('msg'); if(user_pw.value.length < 6){ msg.textContent = '비밀번호는 6글자 이상이어야합니다.'; } else { msg.textContent = ''; } } </script> </body> </html>
 
  • 마우스 이벤트 CODE - mouseover, mouseout
<!DOCTYPE html> <html> <head> <title>Document</title> </head> <style> div{ border : solid 1px #dbdbdb; width: 150px; height: 150px; } #box { } </style> <body> <div id="box"> </div> <script> var box = document.getElementById('box'); box.addEventListener('mouseover', over); box.addEventListener('mouseout', out); function over(){ box.style.backgroundColor = 'blue'; } function out(){ box.style.backgroundColor = 'white'; } </script> </body> </html>
 
  • 스크롤 이벤트
<!DOCTYPE html> <html> <head> <title>Document</title> </head> <style> div{ border : solid 1px #dbdbdb; width: 150px; height: 150px; } #one { background-color: blue; } #one.on { position: fixed; } #two { background-color: red; } </style> <body> <div id="one"></div> <div id="two"></div> <div id="two"></div> <div id="two"></div> <div id="two"></div> <div id="two"></div> <div id="two"></div> <script> //요소를 선택하는 또 다른 방법 : querySelector var one = document.querySelector('#one'); //스크롤 시 파란색 박스만 고정 function scroll() { //pageYOffset : 스크롤바의 offset 반환 //console.log(pageYOffset); if(pageYOffset >= 10){ one.classList.add('on'); } else { one.classList.remove('on'); } } window.addEventListener('scroll', scroll); </script> </body> </html>