Events and Other DOM Properties

The change in the state of an object is known as an Event. In html, there are various events which represents that some activity is performed by the user or by the browser. When javascript code is included in HTML, js react over these events and allow the execution. This process of reacting over the events is called Event Handling. Thus, js handles the HTML events via Event Handlers.

For example, when a user clicks over the browser, add js code, which will execute the task to be performed on the event. Some of the HTML events and their event handlers are:

<body>
    <h2>JS HTML Events</h2>
    <button onclick="document.getElementById('demo').innerHTML=Date()">current time is?</button>
    <p id="demo"></p>
</body>

Mouse events

Event Performed Event Handler Description
click onclick When mouse click on an element
mouseover onmouseover When the cursor of the mouse comes over the element
mouseout onmouseout When the cursor of the mouse leaves an element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
mousemove onmousemove When the mouse movement takes place.

Keyboard events

Event Performed Event Handler Description
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

Form events

Event Performed Event Handler Description
focus onfocus When the user focuses on an element
submit onsubmit When the user submits the form
blur onblur When the focus is away from a form element
change onchange When the user modifies or changes the value of a form element

Window/Document events

Event Performed Event Handler Description
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the browser unloads it
resize onresize When the visitor resizes the window of the browser
<body>
    <button>Change color</button>
</body>
<style>
    button {
        margin: 10px;
    }
</style>
<script>
    const btn = document.querySelector("button");

    function random(number) {
        return Math.floor(Math.random() * (number + 1));
    }
                    
    btn.addEventListener("click", () => {
        const rndCol = `rgb(${random(255)}, ${random(255)}, ${random(255)})`;
        document.body.style.backgroundColor = rndCol;
    });                    
</script>
addEventListener()

The addEventListener() method is used to attach an event handler to a particular element. It does not override the existing event handlers. Events are said to be an essential part of the JavaScript. A web page responds according to the event that occurred. Events can be user-generated or generated by API's. An event listener is a JavaScript's procedure that waits for the occurrence of an event.

The addEventListener() method is an inbuilt function of JavaScript. We can add multiple event handlers to a particular element without overwriting the existing event handlers.

Example

To see the effect when we click on the button.

<body>
    <p>Example of the addEventListener() method.</p>
    <p>Click the following button to see the effect.</p>
    <button id="btn">Click me</button>
    <p id="para"></p>
</body>
<script>
    document.getElementById("btn").addEventListener("click", fun);
    function fun() {
        document.getElementById("para").innerHTML = "Namaste" + "<br>" + "Welcome to the JavaScript Documentation";
    }
</script>

Output:

output

After clicking on the button, the output will be-

output

Example

Multiple events of a different type to the same element.

<body>
    <p>Example of adding multiple events of different type to the same element.</p>
    <p>Click the following button to see the effect.</p>
    <button id="btn">Click me</button>
    <p id="para"></p>
</body>
<script>
    function func() {
        btn.style.width = "50px";
        btn.style.height = "50px";
        btn.style.background = "yellow";
        btn.style.color = "blue";
    }
                      
    function func1() {
        document.getElementById("para").innerHTML =  "This is second function";
    }
                      
    function func2() {
        btn.style.width = "";
        btn.style.height = "";
        btn.style.background = "";
        btn.style.color = "";
    }
                      
    var mybtn = document.getElementById("btn");
    mybtn.addEventListener("mouseover", func);
    mybtn.addEventListener("click", func1);
    mybtn.addEventListener("mouseout", func2);
</script>

Output:

output

When we hover on the button, the output will be-

output

After clicking on the button, the output will be-

output

Proper code:

<script>
    let button = document.getElementById('btn');

    let x = function(e) {
        // console.log(e);
        // console.log(e.target);
        // console.log(e.path);
        // console.log(e.type, e.clientX, e.clientY);
        // console.log(e.currentTarget);
        alert('hello!');
    };

    let y = function(e) {
        alert('hey!');
    };

    button.addEventListener('click', x);

    button.addEventListener('click', y);

    let a = prompt("1 or 2?");

    // below will not work
    // if (a == '2') {
    //   button.removeEventListener('click', function(e) {
    //      alert('hello!');
    //   });
    // }

    if (a == '2')
        button.removeEventListener('click', x);
</script>