addEventListener

hannaha88

hannaA

Posted on July 19, 2022

addEventListener

HTML codes

<div id='container'>
      container
</div>
Enter fullscreen mode Exit fullscreen mode

addEventListener function

this function listens to the event which is passing through the first parameter
and calls a function which passes through the second parameter


const container = document.getElementById("container");
container.style.backgroundColor = "pink";


function backgroundToBlue(event) {
    event.target.style.backgroundColor = "blue";
}
    container.addEventListener("mouseover", backgroundToBlue);

Enter fullscreen mode Exit fullscreen mode

addEvent "mouseleave"


const container = document.getElementById("container");
container.style.backgroundColor = "pink";


function backgroundToBlue(event) {
    event.target.style.backgroundColor = "blue";
}

function backgroundToPink(event) {
    event.target.style.backgroundColor = "pink";
}

container.addEventListener("mouseover", backgroundToBlue);
container.addEventListener("mouseleave", backgroundToPink);

Enter fullscreen mode Exit fullscreen mode

add randomColor to the target and body


const container = document.getElementById("container");
container.style.backgroundColor = "pink";


function backgroundToNext(event) {
    const randomColor = Math.floor(Math.random()*16777215).toString(16);
    event.target.style.backgroundColor = "#" + randomColor;
}

const setBg = () => {
    const randomColor = Math.floor(Math.random()*16777215).toString(16);
    document.body.style.backgroundColor = "#" + randomColor;
    color.innerHTML = "#" + randomColor;
}

container.addEventListener("mouseover", setBg);
container.addEventListener("mouseover", backgroundToNext);

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
hannaha88
hannaA

Posted on July 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related