Javascript Events

Code Snippets Events
Share:

About

In this code snippet, we’ll learn about events in Javascript.

We can add and subsequently remove event listeners(of different types: click, change, mouseenter, …) to any element of our choosing. These event listeners will wait for the specified event(like clicking on an element) to occur. When finally it does the event listener will call/execute the code we specified beforehand.  

Let’s see the code example below.

Code:

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>DOM Manipulation</title>
    </head>
    <script src="code.js"></script>
    <script>
        function sayThanks(){
            alert("Thanks.");
        }
    </script>
    <body>
        <div>
            <div style="background-color: blue; width: 100px; height: 100px;"></div>
            <!-- Events can also be registered like so(but the function must be defined in this file!): -->
            <h1 onclick="sayThanks()">Please click me.</h1>
            <h1 onclick="this.innerHTML = 'Thanks.'">Please click me.</h1>
        </div>
    </body>
</html>
code.js
//Run this when the HTML gets loaded.
window.onload = () => {

    //Add event listener. //Possible events: "click", "mouseenter", "mouseleave", "change", "keydown", "load"
    document.getElementById("coloredDiv").addEventListener("click", changeColor);
    
    //Remove event listener.
    //document.getElementById("coloredDiv").removeEventListener("click", changeColor);

    function changeColor(eventArgs){
        //eventArgs.currentTarget will return the element that was clicked.
        //Then we can simply use .style.backgroundColor to change its color.
        eventArgs.currentTarget.style.backgroundColor = "red";
    }
}

Resulting output:

Before:
After:
Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger