Dev/JavaScript

[JavaScript] Events

코딩삐약 2022. 4. 27. 17:00
const h1 = document.querySelector("div.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("all good!");
}
// 개체.addEventListener(event명, 함수);
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);

 

const h1 = document.querySelector("div.hello:first-child 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);


/*
step 1. Find the Element.
step 2. Listen for an event.
step 3. React to the event.
*/