JavaScript

[JavaScript] Event

개발자 마멋 2023. 11. 10. 22:25

Event

- 클릭 하는 것, 마우스가 특정 위치에 올라가는 것, 이름 적는 것 등 대부분 모든 것이 event

- console.dir을 사용해서 코드 내부를 보면 on으로 시작하는 것들이 event listener


HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>valila js</title>
</head>
<body>
    <div class="hello">
    <h1>click me!</h1>
    </div>
    <script src="web.js"></script>

</body>
</html>

eventListener

addEventListener

- 지정하는 이벤트를 감지하고 행동

- .removeEventListener 사용해서 제거 가능


Click, mouse event

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

function handleTitleClick() {
    console.log("title was clicked!");
}

title.addEventListener("click", handleTitleClick); // 클릭하는 이벤트를 알아보는 것을 명시

/* title 클릭 시 : title was clicked! */

 

("click", handleTitleClick) : h1이 클릭 되면 handleTitleClick 함수를 실행

 

응용

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

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

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

function handleMouseLeave() {
    title.innerText = "Mouse is gone!";
}
title.addEventListener("click", handleTitleClick);
title.addEventListener("mouseenter", handleMouseEnter);
title.addEventListener("mouseleave", handleMouseLeave);

 

mouseenter : 지정한 곳에 마우스를 가져가면 실행

mouseleave : 지정한 곳에서 마우스를 다른 곳으로 이동시키면 실행

 

on을 활용한 방법

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

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

title.onclick = handleTitleClick
/* 결과 동일 */

 


window event

resize

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

function handleWindowResize() {
    document.body.style.backgroundColor = "tomato";
}

window.addEventListener("resize", handleWindowResize);

 

윈도우(웹페이지)의 사이즈가 변경되면 body의 배경이 토마토 색으로 변경

 

copy

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

function handleWindowCopy() {
    alert("copier!")
}
window.addEventListener("copy", handleWindowCopy);

 

복사한 것이 인식되면 경고창 출력


connection event

WIFI (offline, online)

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

function handleWindowOffline() {
    alert("SOS no WIFI");
}

function handleWindowOnline() {
    alert("all good");
}

window.addEventListener("offline", handleWindowOffline)
window.addEventListener("online", handleWindowOnline)

 

와이파이 연결 상태에 따른 경고창 출력

let textNodes = document.querySelectorAll("div.tt_article_useless_p_margin.contents_style > *:not(figure):not(pre)"); textNodes.forEach(function(a) { a.innerHTML = a.innerHTML.replace(/`(.*?)`/g, '$1'); });