본문 바로가기

프론트엔드/javascript

javascript (6) - click event, window event

* 사용가능한 event 목록 찾기

1. google - h1 html element mdn (Mozilla Developer Network) 검색

- HTMLHeadingElement - Web APIs | MDN 사이트

2. vscode - console.dir(title); 입력 // const tilte = ~~

- on-abort처럼 목록앞에 on이 붙은 것들은 사용할수 있는 evnet

 

*click = 클릭했을 때 이벤트 발생

mouseenter = 마우스 올려 두면 이벤트 발생

mouseleave = 마우스 벗어나면 이벤트 발생

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

console.dir(title);

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); //마우스 벗어나면
title.addEventListener("click", handleTitleClick); //클릭
title.onclick=handleTitleClick; //클릭 위와 같은 결과 

*addEventListener 선호하는 이유? removeEventListener을 사용할 수 있다.

 

*resize = 창 크기 변경, copy = 복사하기

offline, online = 와이파이 연결 유/무

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

console.dir(h1);

function handleTitleClick() {
    h1.style.color = "blue";
}
function handleMouseEnter() {
    h1.innerText = "Mouse is here!";
}
function handleMouseLeave() {
    h1.innerText = "Mouse is gone!";
}

function handleWindowResize() {
    document.body.style.backgroundColor = "tomato";
}
function handleWindowCopy() {
    alert("copier!");
}
function handleWindowOffline() {
    alert("SOS no WIFI");
}
function handleWindowOnline() {
    alert("Connet WIFI");
}

h1.addEventListener("click", handleTitleClick);
h1.addEventListener("mouseenter", handleMouseEnter);
h1.addEventListener("mouseleave", handleMouseLeave);

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

documentbody, head, title은 가져올 수 있고 나머지 요소들은 queryselector로 찾아야함

 

*클릭했을 때 파랑색, 오렌지색 번갈아가며 변경하기 - if()사용

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

console.dir(h1);

function handleTitleClick() {
    const currentColor = h1.style.color;
    let newColor;
    if (currentColor === "blue") {
        newColor = "tomato";
    }
    else {
        newColor = "blue";
    }
    h1.style.color = newColor;
}


h1.addEventListener("click", handleTitleClick);

But, Style은 css에서 해주는게 적합! 

js로 Style 변경은 별로 css가 있기 때문에

javaScript는 Animator

반응형