JavaScript Events

Events are actions or occurrences that happen in the browser, triggered by user interactions or system events.

JavaScript allows developers to capture and respond to these events, enabling dynamic and interactive web applications.

Let's explore the various aspects of events with code examples:

Event Handlers

Event handlers are functions that execute in response to a specific event.

They are typically assigned to HTMLelements and are triggered when the corresponding event occurs.

<button onclick="alert('Button clicked!')">Click me</button>

In the above example, the onclickevent handler is assigned to a button element. When the button is clicked, the alert()function is invoked, displaying a message.

Event Listeners

Event listeners are a more flexible and preferred way of handling events in JavaScript.

They allow multiple event handlers to be attached to an element, and they provide greater control over event propagation.

<button id="myButton">Click me</button>


document.getElementById("myButton").addEventListener('click', function(){
  alert("Button clicked!");
})

In the above example, an event listener is added to the button element with the addEventListener()method. When the button is clicked, the specified callback function is executed.

Example


<html>
  <head>
    <title>Title</title>
  </head>
  <body>
    <button id="myButton">Click me</button>    
  <script>
      document.getElementById("myButton").addEventListener('click', function(){
        alert("Button clicked!");
      })
  </script>
  </body>
</html>

Event Object

When an event occurs, an event object is created that contains information about the event.

Developers can access this object to retrieve details such as the type of event, the target element, and any additional data associated with the event.

<button id="myButton">Click me</button>


document.getElementById("myButton").addEventListener('click', function(event){
  alert("Button clicked by " + event.target.id);
})

In the above example, the event object eventis passed to the event handler function. The targetproperty of the event object refers to the element that triggered the event.

Example


<html>
  <head>
    <title>Title</title>
  </head>
  <body>
    <button id="myButton">Click me</button>    
    <script>
      document.getElementById("myButton").addEventListener('click', function(event){
        alert("Button clicked by " + event.target.id);
      })
  </script>
  </body>
</html>

Event Propagation

Events in JavaScript follow a process called event propagation, which consists of two phases: capturing and bubbling.

Event propagation determines the order in which event handlers are executed when an event occurs on a nested element.


<div id="outer">
  <div id="inner">Click me</div>
</div>


document.getElementById("outer").addEventListener('click', function(){
  alert("Outer div clicked!");
}, true)

document.getElementById("inner").addEventListener('click', function(){
  alert("Inner div clicked!");
})

In the above example, the event handler attached to the outer div uses event capturing (specified by the third parameter true), while the event handler attached to the inner div uses event bubbling.

Example

<html>
  <head>
    <title>Title</title>
  </head>
  <body>
    <div id="outer">
      <div id="inner">Click me</div>
    </div>
    <script>
      document.getElementById("outer").addEventListener('click', function(){
        alert("Outer div clicked!");
      }, true)
    
      document.getElementById("inner").addEventListener('click', function(){
        alert("Inner div clicked!");
      })
  </script>
  </body>
</html>

The order of execution of event handlers depends on the phase of event propagation.

Events play a crucial role in creating interactive and dynamic web applications.

As you can tell from the input examples, Javascript is an event driven language which means your scripts react to events you set up.

Your code isn't running all the time, it simply waits until an event starts something up! Going into all the Javascript events is beyond the scope of this document but here's a short-list of common events to get you started.

There are more options of event that you can use instead of click, here are few of them:

Event Description
onAbort An image failed to load.
onBeforeUnload The user is navigating away from a page.
onBlur A form field lost focus (User moved to another field).
onChange The contents of a field has changed.
onClick User clicked on this item.
onDblClick User double-clicked on this item.
onError An error occurred while loading an image.
onFocus User just moved into this form element.
onKeyDown A key was pressed.
onKeyPress A key was pressed OR released.
onKeyUp A key was released.
onLoad This object (iframe, image, script) finished loading.
onMouseDown A mouse button was pressed.
onMouseMove The mouse moved.
onMouseOut A mouse moved off of this element.
onMouseOver The mouse moved over this element.
onMouseUp The mouse button was released.
onReset A form reset button was pressed.
onResize The window or frame was resized.
onSelect Text has been selected.
onSubmit A form's Submit button was pressed.
onUnload The user is navigating away from a page.

These events can be attached to most any HTML tag or form element. Of them all onClickwill probably be what you end up using most often.