Javascript Events

Code Snippets Events


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.


<!DOCTYPE html>
        <title>DOM Manipulation</title>
    <script src="code.js"></script>
        function sayThanks(){
            <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>
//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. = "red";

Resulting output:


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