The Web Developer 부트캠프 2022

JS addEventListener

거위발바닥 2022. 9. 23. 00:59
const btn = document.querySelector('#v2')

btn.onclick = function () {
    console.log("you clicked me!")
    console.log("i hope it worked!!")
} // btn 버튼을 눌렀을때 함수가 실행되어 console.log로 string이 뜬다.

function scream() {
    console.log("AAAAAHHHH");
    console.log("STOP TOUCHGING ME!")
}
btn.onmouseenter = scream; 
// btn에 마우스 enter 즉, 마우스를 올렸을때 scream 함수가 실행된다.

document.querySelector('h1').onclick = function () {
    alert('you clicked the h1!');
} // h1을 눌렀을때 함수가 실행된다.

기본적인 onclick button 이벤트이다.

const btn3 = document.querySelector('#v3');
btn3.addEventListener('click', function () {
    alert("CLICKED!!!!");
}) // onclick 같은 코드가 아닌 addEventListener에 event 
   //'click' 을 넣고 실행할 함수를 넣음으로써 onclick과 같은 역할을 해준다.

기본적인 위 onclick 이벤트보다 더 좋다.

function twist() {
    console.log("TWIST!!")
}
function shout() {
    console.log("SHOUT!!")
} // 버튼을 하나 클릭해서 위의 두 함수를 같이 실행시키고 싶다고 할때

btn3.addEventListener('click', twist)
btn3.addEventListener('click', shout) 
// addEventListener 방식으로는 이렇게하면 twist와 shout가 버튼 한번 누르면 동시에 실행된다.
// 하지만 이 방법은 일반적인 onclikc 방식으로는 불가능하다.

btn3.addEventListener('click', twist, {once : true})
// 위 같이 addEventListener 방식으로는 뒤 {onece : true} 를 넣으면 
// 해당 버튼을 한번 클릭하면 위 함수가 실행된 후 해당 이벤트는 삭제된다.

 

'The Web Developer 부트캠프 2022' 카테고리의 다른 글

JS 폼 활용  (1) 2022.09.23
JS 이벤트 객체와 keydown  (0) 2022.09.23
JS CSS STYLE, classList  (0) 2022.09.23
포켓몬 데모  (0) 2022.09.22
JS CSS STYLE, classList, 계층이동, 삭제  (0) 2022.09.22