바닐라JS - event

김현수·2022년 8월 22일

바닐라JS

목록 보기
10/17

event

이벤트는 엄청 다양하게 존재
property 이름 앞에 on이 붙어있다면 event listener.

1) click event

엘리먼트를 클릭했을 때 발생하는 이벤트

HTML엘리먼트.addEventListener("click", 호출할 function)

ex)

const title = document.querySelector("div.hello:first-child h1");

function handleTitleClick() {
	title.style.color = "blue";
}

title.addEventListener("click", handleTitleClick)
// = title.onclick = handleTitleClick;

2) mouseenter event

마우스가 엘리먼트 위에 올라갔을 때 발생하는 이벤트

HTML엘리먼트.addEventListener("mouseenter", 호출할 function)

ex)

const title = document.querySelector("div.hello:first-child h1");

function handleMouseEnter() {
	title.innerText = "Mouse is here!";
}

title.addEventListener("mouseenter", handleMouseEnter);
// = title.onmouseenter = handleMouseEnter;

3) mouseleave event

마우스가 엘리먼트 위에서 나갈 때 발생하는 이벤트

HTML엘리먼트.addEventListener("mouseleave", 호출할 function)

ex)

const title = document.querySelector("div.hello:first-child h1");

function handleMouseLeave() {
	title.innerText = "Mouse is gone!";
}

title.addEventListener("mouseLeave", handleMouseLeave);
// = title.onmouseleave = handleMouseLeave;

4) window event

function handleWindowResize() {// window창의 크기가 바꼈을때
	document.body.style.backgroundColor = "tomato";
}
function handleWindowCopy() {// 유저가 copy 행위를 했을때
	alert("copier!");
}
function handleWindowOffline() {// wifi 연결 해제 되었을 때
	alert("SOS no WIFI!");
}
function handleWindowOnline() {// wifi 연결 되었을 때
	alert("ALL GOOOD!");
}

window.addEventListener("resize", handleWindowResize);
window.addEventListener("copy",handleWindowCopy);
window.addEventListener("offline", handleWindowOffline);
window.addEventListener("online", handleWindowOnline);

0개의 댓글