CommonLounge Archive

JavaScript: Event handling

September 26, 2018

In the previous tutorial, you saw how to edit HTML using JavaScript.

In this tutorial, you will learn how to trigger a JavaScript function to run when a user does something, such as click on a button. This will allow you to change the HTML page in reaction to actions taken by the user on your website.

User clicking on a button is one of many types of events supported by JavaScript. You’ll see another event in the next tutorial — submitting forms. And then many more over the remaining tutorials in this course.

Overview

As a small example of how to trigger JavaScript functions when an event happens, we will start by making an HTML page which changes when the user clicks a button. To do this, we need to do the following:

  • Create an HTML page with a <button> element
  • Write a JavaScript function to change the style properties of <body>
  • Connect the button to the JavaScript function.

Let’s get started!

Step 1: HTML page with Button

<html>
    <head>
        <title>Introduction</title>
    </head>
    <body style="background: lightgreen;">
        <b style="font-size: 40px;">
            Hello World!
        </b>
        <p>
            Random sentences with no meaning coming up... <br>
            Attention he extremity unwilling on otherwise. 
            Conviction up partiality as delightful is discovered. <br>
            <i> Fin </i>
        </p>
        <button>
            Toggle background color
        </button>
    </body>
</html>

This button doesn’t do anything right now; HTML only defines the structure. We will have to write some JavaScript to make it functional.

Step 2: Writing JavaScript

Let’s write a JavaScript function, togglebackgroundcolor(), which will toggle the background color of our page between lightgreen and beige.

<html>
    <head>
        <title>Introduction</title>
        <script>
            function togglebackgroundcolor() {
                // document.body returns the body tag
                var bodytag = document.body;
                var backgroundColor = bodytag.style.background;
                // if background is lightgreen set it to beige
                if (backgroundColor === "lightgreen")
                    bodytag.style.background = "beige";
                // else if background is beige set it to lightgreen
                else if (backgroundColor === "beige")
                    bodytag.style.background = "lightgreen";
            }
        </script>
    </head>
    <body style="background: lightgreen;">
        <b style="font-size: 40px;">
            Hello World!
        </b>
        <p>
            Random sentences with no meaning coming up... <br>
            Attention he extremity unwilling on otherwise. 
            Conviction up partiality as delightful is discovered.
            Yet jennings resolved disposed exertion you off.
            Left did fond drew fat head poor. <br>
            <i> Fin </i>
        </p>
        <button>
            Toggle background color
        </button>
    </body>
</html>

As you saw in the previous tutorial, document.body gives the reference to the <body> tag. The style property of the body tag can be accessed using .style and same for background (.background).

Then, if the background color is beige, we change it to lightgreen. If it is lightgreen then we change it to beige.

Open this in a browser and try clicking the button now. It is still not working! That is because we haven’t defined when to run this function. For that, we need to set the function to be executed when the button is clicked.

Step 3: Connecting the button to the JavaScript function

Most HTML elements have certain attributes which can be used to trigger JavaScript functions. These attributes are called event attributes. There are attributes like onclick, onmousemove, onload, onchange etc.

We will use the onclick attribute inside the <button> tag to execute the function. So we need to change,

<button>

to

<button onclick="togglebackgroundcolor()">

It is that simple. Just specify the name of the JavaScript function to be executed onclick.


The final HTML looks as follows. Save it as events.html and open it in your browser.

<html>
    <head>
        <title>Introduction</title>
        <script>
            function togglebackgroundcolor() {
                // document.body returns the body tag
                var bodytag = document.body;
                var backgroundColor = bodytag.style.background;
                // if background is lightgreen set it to beige
                if (backgroundColor === "lightgreen")
                    bodytag.style.background = "beige";
                // else if background is beige set it to lightgreen
                else if (backgroundColor === "beige")
                    bodytag.style.background = "lightgreen";
            }
        </script>
    </head>
    <body style="background: lightgreen;">
        <b style="font-size: 40px;">
            Hello World!
        </b>
        <p>
            Random sentences with no meaning coming up... <br>
            Attention he extremity unwilling on otherwise. 
            Conviction up partiality as delightful is discovered. <br>
            <i> Fin </i>
        </p>
        <button onclick="togglebackgroundcolor()">
            Toggle background color
        </button>
    </body>
</html>

Open the page now and you should see the background color toggle when you click the button.

Awesome, right?


Similarly, we can change any other properties that we would like to, or do anything else we would like to in the page.

Try out somethings that you learnt in the previous tutorial. Play with it for a bit, and get back here when you are done.


Apart from the onclick event for buttons, JavaScript has hundreds of events which get triggered when something happens. Some of these are based on user actions, such as moving the mouse, scrolling, clicking, typing, etc. Others are based on system information, such as network getting disconnected. Here’s the detailed documentation on all the available GlobalEventHandlers.

Hiding an element

There’s are a couple of style properties which deserves special mention — display and visibility.

If display is set to none, the element is removed from the page. display = none, removes the element from the page and the space it used to occupy is now filled with the elements below it.

The visibility property can be set to hidden or visible to hide or show an element. visibility = hidden only hides the element, the element still takes same amount of space.


Instead of only toggling the background color, let’s also hide / show the text “Hello World!” now:

<html>
    <head>
        <title>Introduction</title>
        <script>
            function togglebackgroundcolor() {
                // document.body returns the body tag
                var bodytag = document.body;
                var backgroundcolor = bodytag.style.background;
                var btag = document.getElementsByTagName("b")[0];
                // if background is lightgreen set it to beige
                if (backgroundcolor === "lightgreen") {
                    bodytag.style.background = "beige";
                    btag.style.visibility = "hidden";
                }
                // else if background is beige set it to lightgreen
                else if (backgroundcolor === "beige") {
                    bodytag.style.background = "lightgreen";
                    btag.style.visibility = "visible";
                }
            }
        </script>
    </head>
    ...
</html>

Try it out!

Accessing current HTML element with this keyword

this is a reserved keyword in JavaScript. It gives the reference of the current HTML element in context. This will be clear by an example:

<p onmouseover="doSomething(this)">
    ...
</p>
..
<script>
    function doSomething(element) {
        ...
    }
</script>

When mouse is moved over the <p> element, it calls the doSomething() function and passes its own reference as a parameter to the function. This is useful when we wish to use the same JavaScript function for a number of HTML elements. We can pass the same function with the this keyword!

Let’s see how we can use this keyword. Create a new HTML page with a list of 5 <b> elements; pointing mouse at any of these elements should change increase its font-size and change color.

<html>
    <head>
        <title>Changing styles of multiple elements</title>
        <script>
            function doSomething(element, flag) {
            }
        </script>
    </head>
    <body>
        <b onmouseover="doSomething(this, true);" onmouseout="doSomething(this, false);" style="font-size: 20px;">One</b><br>
        <b onmouseover="doSomething(this, true);" onmouseout="doSomething(this, false);" style="font-size: 20px;">Two</b><br>
        <b onmouseover="doSomething(this, true);" onmouseout="doSomething(this, false);" style="font-size: 20px;">Three</b><br>
        <b onmouseover="doSomething(this, true);" onmouseout="doSomething(this, false);" style="font-size: 20px;">Four</b><br>
        <b onmouseover="doSomething(this, true);" onmouseout="doSomething(this, false);" style="font-size: 20px;">Five</b><br>
    </body>
</html>

The function doSomething() has two parameters, element and flag — the element whose styles have to be changed and a boolean variable. If flag is true we will increase the font size and change color to red. If it’s false, we will undo these changes.

Define the function like this:

function doSomething(element, flag) {
    if (flag) {
        element.style.fontSize = "30px";
        element.style.color = "red";
    } else {
        element.style.fontSize = "20px";
        element.style.color = "black";
    }
}

Open this in a browser and you should see the color and font-size change on moving mouse over the <b> elements.

event keyword and event attributes

event is also a reserved keyword in JavaScript. It is a shorthand for the window.event object. It returns the event which is being handled by a function.

MouseEvent

For example:

<p onmouseover="doSomething(event)">
    Hello World!
</p>
...
<script>
    function doSomething(event) {
        console.log(event);
    }
</script>

Move your mouse pointer over the paragraph and you should see something similar to this in the console:

MouseEvent {isTrusted: true, screenX: 41, screenY: 120, clientX: 41, clientY: 24, …}

It returns a MouseEvent object which has various details about the event like, the location of mouse pointer etc.


Let’s see an example where we use the event keyword to get mouse position as it is moved. Create a new HTML file:

<html>
    <head>
        <title>
            Capture mouse motion
        </title>
    </head>
    <body>
        Move your mouse over this rectangle
        <div id="rectangle" style="height: 200px; width: 350px; background: violet;" onmousemove="captureMouse(event);">
        </div>
        <p id="location">
        </p>
    </body>
    <script>
        var locationP = document.getElementById("location");
        function captureMouse(e) {
        }
    </script>
</html>

Define the function captureMouse() as follows:

function captureMouse(e) {
    var string = "Screen coordinates : <br>";
    string += "X = " + e.screenX + "  Y = " + e.screenY + "<br>";
    string += "Window coordinates : <br>"
    string += "X = " + e.clientX + "  Y = " + e.clientY + "<br>";
    locationP.innerHTML = string;
}

We have used two types of coordinates here, (screenX, screenY) and (clientX, clientY). If you resize your browser window, smaller than your screen size then you will see different values for the two pairs of coordinates.

  • screenX and screenY are with respect to your monitor screen, with (0, 0) being the top left of your screen.
  • clientX and clientY are with respect to your browser window, with (0, 0) being the top left of your browser page.

Top left of screen has clientX, clientY = (0, 0).

Live tracking the mouse location! Pretty cool, right?

KeyboardEvent

Similar to the MouseEvent object, there’s a KeyboardEvent object. The event keyword returns a KeyboardEvent when events like keydown, keyup, keypress are triggered. The KeyboardEvent object has details like the key code of the pressed/released key etc.


Let’s see an example where we use a keyboard event:

<html>
    <head>
        <title>
            Keyboard event
        </title>
    </head>
    <body onkeydown="doSomething(event)">
        <p>Press any key on your keyboard (including special keys, like arrays, Shift, etc).</p>
        <p id="res"></p>
        <script>
            var resP = document.getElementById("res");
            function doSomething(event) {
                resP.innerHTML = "Key code of the pressed key: " + event.keyCode;
            }
        </script>
    </body>
</html>

event returns a KeyboardEvent object in this case and event.keyCode returns key code value associated with the pressed key.


For documentation on MouseEvent and KeyboardEvent, see: MouseEvent and KeyboardEvent.

Adding event listeners dynamically using JavaScript

We know that we can create elements dynamically using JavaScript by using the createElement(), appendChild() and insertBefore() methods. We can also assign some function to the event attributes of the dynamically created elements. The JavaScript method addEventListener() attaches an event handler to a particular element.


The general syntax of addEventListener() is:

element.addEventListener("event-name", event-handling-function);
  • "event-name" can take values like "click", "mouseover", "mouseout", "mousemove", "keydown", "keyup" etc.
  • event-handling-function is the function which is called whenever the event is triggered.

For example,

...
<button id="btn"> Click me </button>
...
<script>
    var btn = document.getElementById("btn");
    btn.addEventListener("click", function() { alert("button clicked"); });
</script>

Whenever the button is clicked an alert box pops up with the message “button clicked”.

Here is a detailed list of all JavaScript event types: Event reference. Almost anything you would want to use is listed in the top section, titled ”Most Common Categories“.


You can also directly assign to the appropriate attribute. For example:

btn.onclick = function() { alert("button clicked"); };

Summary

In this tutorial, you learnt

  • events — executing JavaScript functions based on the actions done by the user
  • this keyword — how to access the HTML element on which the action was done using
  • event keyword — how to access event attributes such as location of mouse, or which keyboard keys were pressed

The ideas you learnt about in this tutorial are very powerful. You’re now ready to do some really interesting projects using your JavaScript skills!


© 2016-2022. All rights reserved.