Event Examples By Chloe

Click me to change the background colour!
In the above example, we have used the event listener with the 'click' method to change the background color when clicked. We have also used an arrow function to create the function. The id of the div was 'clkEx'

        let cEx = document.getElementById('clkEx');

        let changeBack = () => {
            cEx.style.backgroundColor = 'orange';
                }

            cEx.addEventListener('click', changeBack);
        
Double click me to see what happens!
In the above example, we used the event listener with the 'dblclick' method. We called a function we created that changed the text and the background colour when double clicked.

    let dblEx = document.getElementById("dblClk");

    let changeDiv = () => {
    dblEx.innerHTML = "WOAH YOU CHANGED MY TEXT!!";
    dblEx.style.background = "red";
    }

    dblEx.addEventListener('dblclick', changeDiv);
    
Hover over me...
In this above example, we have used the 'mouseenter' and 'mouseleave' method in order to create a hover effect. When hovered over we change the style to 'none' so that the div is not displayed. Then when the mouse leaves, the style is changed back to 'block' so that it re-appears.

        let Hver = document.getElementById('hoverEx');

        let change = () => {
        Hver.style.display = 'none';
            }

        let back = () => {
        Hver.style.display = 'block';
            }

        Hver.addEventListener('mouseenter', change);

        Hver.addEventListener('mouseleave', back);
        

event.target

example

for JS

In the above example, we have used the event.target method so that we can set just one event listener on the outer div (id = Examples4), but still reach all 6 nested elements when they are clicked:
        
        let example = document.getElementById('Examples4');

        example.addEventListener('click', e => {
            event.target.innerHTML = "TA-DA!";
                })

        
Click here to return back to the events page!