1 2 3 4 5 6 7 8 | const h1 = document.querySelector('h1'); h1.addEventListener('click', () => { alert("클릭"); //결과 : h1을 클릭하면 "클릭" 이라는 alert 창이 뜬다. }); h1.addEventListener('mouseover', () => { alert("마우스오버"); //결과 : h1을 클릭하면 "마우스오버" 이라는 alert 창이 뜬다. }); |
1 2 3 4 | const h1 = document.querySelector('h1'); h1.onclick = function(){ alert(); //결과 : h1을 클릭하면 alert 창이 뜬다. }; |
1 2 | <h1 onclick="alert();">로고</h1> <!-- 결과 : h1 클릭시 alert 창이 뜬다. --> |
1 2 3 4 5 6 7 8 9 10 11 12 | const h1 = document.querySelector('h1'), btn = document.querySelector('button'); function eventBox(){ alert("이벤트등록"); } h1.addEventListener('click', eventBox); //h1 태그에 클릭 이벤트 등록 btn.addEventListener('click', () => { h1.removeEventListener('click', eventBox); //버튼 클릭하면 h1 태그에 있던 클릭 이벤트가 삭제된다. }); |
1 2 3 4 5 6 7 8 9 10 11 12 | <button type="button">버튼</button> 에 mouseover 이벤트리스너를 추가해보자. <!-- 인라인 이벤트 등록방식 --> <button type="button" onmouseover="abc();" onfocus="abc();">버튼</button> <script> const button = document.querySelector('button'); /* 표준 이벤트 등록방식 */ button.addEventListener("mouseover",abc); button.addEventListener("focus",abc); /* 고전 이벤트 등록방식 */ button.onmouseover = abc; button.onfocus = abc; </script> |
1 2 3 4 5 6 7 8 | function(이벤트객체){ 실행문 } /* 예시 */ document.getElementById("hello").addEventListener('click', function(e){ let a = e.pageX; //결과 : 변수 a에 내가 클릭한 지점의 x 좌표값이 담긴다. }); |
1 2 3 4 5 6 7 8 | <a href="https://www.naver.com/" id="link">네이버</a> <script> const link = document.getElementById("link"); link.addEventListener("click", function(event){ event.preventDefault(); }); </script> |