JavaScript

Event Handlers

Events

An event: a signal that something has happened.

Some most useful DOM Events:

Elements

Some common elements highly related to events and handlers:

Event Handlers

A handler: a function that runs in case of an event.

There are 3 ways to assign event handlers:


HTML-attributes

onevent

<input ... onevent="the-action">

A handler can be set with an attribute named onevent. For example:

Note: We will use onclick a lot to illustrate onevent in this note.

Example:

<input type="button" value="Click me" onclick="alert('It works!')">

DOM Property

<input ... id="idName" >
idName.onevent

A handler can be assign using a DOM property onevent.

Example:

<input type="button" value="Click me" id="handler">

<script>
    handler.onclick = function() {
        alert('This also works!');
    };
</script>

HTML-attributes works like DOM property

<input type="button" onclick="whatever here" ...>

<input type="button" id="button" ...>
<script>
button.onclick = function() {
whatever here;
}

</script>

When a handler is assigned using HTML-attributes, actually the browser creates a new function from the attribute content and writes it to the DOM property.

<input type="button" onclick="alert('Yippie!')" value="Click here">

The HTML attribute is used to initialize button.onclick. It's the same with:

<input type="button" id="button" value="Click here">
<script>
    button.onclick = function() {
        alert('Yippie!');
    }
</script>

Assigning function to DOM Property

idName.onclick = functionName

Important: Pay attention to functionName vs functionName() when assigning existing function to event handler. Like in example below, make sure thanksButton.onclick is sayThanks, instead of sayThanks().

<input type="button" value="Thank you button" id="thanksButton">
<script>
    function sayThanks() {
        alert('Thank you!');
    }

    thanksButton.onclick = sayThanks;
</script>

Assigning function to HTML-attribute

<input type="button" onclick="functionName() ...>

<input type="button" id="button" ...>
<script>
button.onclick = function() {
functionName();
}
</script>

In the other way around, use functionName() for assignment of HTML-attribute handler, because it's essentially going to be rewritten in such way from HTML to Script.

<input type="button" value="Tombol Makasih" onclick="makasih()">
<script>
    function makasih() {
        alert('Terima kasih!');
    }
</script>

Using both HTML-attributes and DOM property

Because only one action/function can happen per event, when both are used, the later one (DOM property on <script>) will overwrite the HTML-attribute.

<input type="button" id="handler2" onclick="alert('First')" value="Click here">
<script>
    handler2.onclick = function() {
        alert('Second');
    }
</script>

Remove handler

idName.onclick = null;

To remove a handler, assign null.

handler2.onclick = null;

Accessing the element: this

this

It's possible for a handler to access the element it's on. It's by using this.

Example:

<button onclick="alert(`Button name: ${this.innerHTML}`)">Kitten</button>

addEventListener

element.addEventListener (event, handler, [options]);
element.removeEventListener (event, handler, [options]);

Problem with previous way, we can't assign multiple handlers to 1 event. The later handler will overwrite the earlier one. Special methods addEventListener and removeEventListener allow multiple handler assignments.

The components:

Removal's handler

Important: Removal requires the same function as the assignment. Function must be passed as a variable.

The right way:

function handler() {
    alert("Kitten");
}

input.addEventListener("click", handler);
// ...
input.removeEventListener("click", handler);

If not, even though we are using the same code, it will be different function object, and removal will fail. Example:

input.addEventListener("click", () => alert("Kitten"));
// ...
input.removeEventListener("click", () => alert("Kitten"));
// The removal doesn't work

Multiple handlers

DOM property and addEventListener can be used together to assign handlers, even though typically only one way is used, and some handlers only work with addEventListener

<input id="countInput" type="button" value="Counting button">

<script>
    function countTwo() {
        alert("Two");
    };

    function countThree() {
        alert("Three")
    }

    countInput.onclick = () => alert("One");
    countInput.addEventListener("click", countTwo);
    countInput.addEventListener("click", countThree);
</script>

More universal

There are some events that can only be assigned using addEventListener. It can't be assigned using DOM property. For example, DOMContentLoaded event that triggers when the document is loaded and DOM is built.


Sandbox

//code

References: