JavaScript Events Explained: Website Reactions to User Actions

JavaScript Events Explained: Website Reactions to User Actions

Learn the ways websites handle user interactions.

·

4 min read

Events

An event is an action that your browser detects and responds to. For example, when you click button like submit in forms, it submits the form.

There are many events that help developers make websites interactive. Lets understand how we can also make our websites interactive.

Some of useful events

Mouse Events :

  • click : This event is triggered when you click on an element like a button or a link.

  • contextmenu : This event is triggered when you right-click on an element.

  • mouseover / mouseout : This event is triggered when the mouse cursor moves over an element or leaves an element.

  • mousedown / mouseup : This event is triggered when a mouse button is pressed down or released over an element.

  • mousemove : This event is triggered when the mouse moves.

Keyboard Events :

  • keyup : When a keyboard key is released

  • keydown : When a keyboard key is pressed

Form Element Events :

  • submit : When a user clicks the submit button on a form

  • focus : When a user focuses on an element like an input field

Document Events :

  • DOMContentLoaded : When the HTML is loaded and processed, the DOM is fully built.

CSS Events :

  • transitionend : When a CSS animation ends

Event Handler

Now that you understand what events are, let's see how you can add them to your website.

To add events, we use Event Handlers. Event handlers are pieces of code, usually functions, that manage events when users interact with the website.

Let's explore different ways to assign handlers to an element.

HTML-attribute

Handler can be assigned to an element’s attribute using on<event>.

For example, we can set an event which display a message when user clicks on a button

<button onclick="alert('Hello Viewer')" >Click Me</button>

When a user clicks on Click Me button, a message will be displayed.

Please note that inside onclick, you should use single quotes because the attribute itself is inside double quotes. If we use double quotes inside the onclick attribute like this onclick="alert("Hello Viewer")", it will not work correctly.

The HTML attribute is not the right place to write large amounts of code. Instead, you should use JavaScript to write the functions and then call them from here.

For instance,

<button onclick="displayMessage()" >Click Me</button>
<script>
    function displayMessage() {
        alert("Hello Viewer")
    }
</script>

As we know HTML attributes are not case sensitive, then we can use ONclick or onClick, or ONCLICK, … But we should always use lower case onclick.

DOM property

We can use DOM property onclick to handle the events.

For instance, element.onclick :

<button id="btn">Click Me</button>
<script>
    const button = document.getElementById("btn")
    btn.onclick = function() {
        alert("Hello Viewer")
    }
</script>

This code works exactly the same as previous one. The only difference is the syntax.

We can add only one event handler on an element.

In this below example, function in script overrides the existing event handler

<button id="btn" onclick="alert('Hello Viewer')">Click Me</button>
<script>
    const button = document.getElementById("btn")
    btn.onclick = function() {
        alert("Hello Viewer")
    }
</script>

To remove a handler – assign elem.onclick = null.

Accessing the element : this

We can access the current element where we apply the event handler using the this keyword. This will refer to the element that has the handler.

For example,

<button onclick="alert(this.innerHTML)"> Click Me </button>

In above code, button shows the content of button when clicked.

Possible Mistakes

There are some mistakes you might make when you're just starting with event handlers. Let's explore what these mistakes are.

<button id="btn">Click Me</button>
<script>
    const button = document.getElementById("btn")

    button.onclick = displayMessage;

    const displayMessage = function() {
        alert("Hello Viewer")
    }
</script>

In this code, we assign the existing function to the handler.

However, you should not use button.onclick = displayMessage() because when you use parentheses, you call the function immediately. The function returns the value of the last line, which is undefined, and this value is stored in onclick. As a result, this will not work.

// wrong
button.onclick = displayMessage()

// right
button.onclick = displayMessage

But when we use an event handler in HTML, we include parentheses because it needs them.

<button onclick="displayMessage()">Click Me</button>

Don’t use setAttribute to set the event handlers.

document.body.setAttribute("onclick", function() { alert("Hello Viewer") })

This doesn't work because setAttribute uses a string, so the function also becomes a string.

DOM property is case sensitive.

Like in HTML, where event handlers are not case-sensitive, DOM properties are case-sensitive. So, we need to use onclick.

Conclusion

In conclusion, understanding JavaScript events and how to handle them is crucial for creating interactive and dynamic websites. By utilizing various event types such as mouse, keyboard, form, document, and CSS events, developers can enhance user experience and engagement. Event handlers, whether assigned through HTML attributes or DOM properties, allow developers to manage these interactions effectively. It's important to be aware of common mistakes, such as incorrect function assignments and case sensitivity issues, to ensure smooth functionality. Mastering these concepts will empower developers to build responsive and user-friendly web applications.