addEventListener
์ mouse event๋ฅผ ์ฌ์ฉํด๋ณด์๋ค.
์ฌ์ฉํด ๋ณธ ์ด๋ฒคํธ ์ค ์ผ๋ถ ์ฝ๋๋ฅผ ์ ์ฅ์ฉ์ผ๋ก ์ฌ๋ฆฐ๋ค. :D
์ผ๋จ ์๋์ ์ฝ๋๋ ์ผ๋ฐ์ ์ผ๋ก ๋ด๊ฐ ์ผ๊ณ , ์ฒ์์ ๋ง๋ค์๋ ์ฝ๋.
const colors = ["#", "#", "#", "#", "#"];
const mouseEvent = document.querySelector("h2");
// mouseenter, mouseleave, contextmenu, resize
function enter() {
// console.log(mouseEvent);
// console.log(colors[0]);
mouseEvent.textContent = "Mouse here!";
mouseEvent.style.color = colors[0];
}
function leave() {
mouseEvent.textContent = "Mouse gone!";
mouseEvent.style.color = colors[1];
}
function rightClick() {
mouseEvent.textContent = "Right click!";
mouseEvent.style.color = colors[4];
}
function resize() {
const width = window.innerWidth;
// console.log(width);
if (width > 1000) {
mouseEvent.style.color = colors[3];
mouseEvent.textContent = "Resized!";
}
}
mouseEvent.addEventListener("mouseenter", enter);
mouseEvent.addEventListener("mouseleave", leave);
window.addEventListener("contextmenu", rightClick);
window.addEventListener("resize", resize);
๊ทธ๋ฆฌ๊ณ ์๋์ ์ฝ๋๋ ๊ฐ์ฒด(object) ์์ ์ ๋ถ ํธ๋ค๋งํ ๋ฒ์ .
์ฒ์์ ์์ ์ฝ๋ ๋๋ก ์์ฑํ๋ค๊ฐ const ์์ ์ด๋ป๊ฒ ๋ฃ์ง..? ์ถ์๋ค. ๐
๊ตฌ์กฐ๋ ๐์ฌ๊ธฐ์์ ํ์ธํ ์ ์๋ค!
const EventHandler = {
enter() {
mouseEvent.textContent = "Mouse here!";
mouseEvent.style.color = colors[0];
},
leave() {
mouseEvent.textContent = "Mouse gone!";
mouseEvent.style.color = colors[1];
},
rightClick() {
mouseEvent.textContent = "Right click!";
mouseEvent.style.color = colors[2];
},
resize() {
const width = window.innerWidth; //x
// console.log(width);
if (width > 1000) {
mouseEvent.style.color = colors[3];
mouseEvent.textContent = "Resized!";
} else {
mouseEvent.style.color = colors[4];
mouseEvent.textContent = "Resized!";
}
},
};
mouseEvent.addEventListener("mouseenter", EventHandler.enter);
mouseEvent.addEventListener("mouseleave", EventHandler.leave);
window.addEventListener("contextmenu", EventHandler.rightClick);
window.addEventListener("resize", EventHandler.resize);
EventHandler
์์ ํจ์๋ ์ ์์ฑํ๊ฑฐ๊ฐ์๋ฐ, ์ ์๊พธ ์ ๋ ๊น.
์ด์ ๋ ๋งจ ์๋ ์ฝ๋๋ค์ด์๋ค.
EventHandler
์์์ ์คํ๋๋ ํจ์์ด๋,
๋งจ ์์ ์ฝ๋์ฒ๋ผ ๊ทธ๋ฅ ("mouseenter", enter);
๋ผ๊ณ ํ๋ฉด ๋ชป ์์๋ฃ๋๋ค.
๊ทธ๋์ EventHandler.enter
๋ผ๊ณ ์
๋ ฅํด์ฃผ์ด์ผ ํ๋ค.
๋ง์ ๋ฐ๊ฟ๋๊ณ ๋ค์ ์ฝ๋๋ฅผ ์ดํด๋ณด๋ฉด
์คํ๋ ํจ์์ ๊ฒ๋ชจ์ต๊ณผ EventListener๋ฅผ ์ถ๊ฐํ ๋ ์์ธ ์์น๋ง ๋ฐ๋์๋ค.
ํน์๋ addEventListener()
๋ฅผ ์ฌ์ฉํ ๋ ์ ๋ ๊ฒ ๊ฐ์ฒด ์์ ๋ฃ๊ฒ๋๋ฉด ์ด๋ฒ ๊ธ์ ์ฐธ๊ณ ํ๋ฉด ๋ ๋ฏํ๋ค. ^_~