Skip to content

Events

An event can be triggered by the user (mouse click, key press) or by the developer.

There are many events, we will see some of the most important ones here.

Listening to the 'click' Event

The developer may want to invoke a function when clicking on an element of the page.

To do this, an event listener must be added and given a callback function to execute:

html
<html>
  <head>
    <title>Simple Example of 'click' Event Handling</title>
  </head>
  <body>

    <h1>Events</h1>

    <button id="btn">
      Click here to increment the counter
    </button>

    <p id="result">
    </p>

    <script>
      document.querySelector('#btn') // Retrieving the element with id 'btn'
        .addEventListener(           // Adding an event listener...
          'click',                   // ...of type 'click'...
          function (event) {         // ...with a callback function
            console.log('Button clicked!')
            setCounter(1 + parseInt(resultEl.innerHTML))
          }
        )
      const resultEl = document.querySelector('#result')
      function setCounter (init = 0) {
        let counter = init
        resultEl.innerHTML = counter
      }
      setCounter()
    </script>
  </body>
</html>

'blur', 'focus', 'input' and 'submit' events

It is usually useful to listen to 'blur', 'focus', and 'input' events of <input>, <select>, or <textarea> tags, as well as the 'submit' of a <form> tag.

vue
<script lang="ts" setup>
import { ref } from 'vue'

const name = ref('')
const lastMessage = ref('')

function onSubmit() {
  lastMessage.value = `Submitted: name=${name.value}`
}
</script>

<template>
  <div>
    <form @submit.prevent="onSubmit">
      <label for="name">
        Name:
      </label>
      <input
        id="name"
        v-model="name"
        placeholder="Alan Smithee"
        @blur="lastMessage = 'field lost focus'"
        @focus="lastMessage = 'field acquired focus'"
        @change="lastMessage = 'field value changed'"
        @input="lastMessage = 'field value may have changed'"
      >

      {{ name }}
      <p class="my-4">
        <button type="submit">
          Send
        </button>
      </p>
    </form>
    <p>
      {{ lastMessage }}
    </p>
  </div>
</template>

<style scoped>
input, button {
  padding: 0.25rem 0.5rem;
  border: 1px solid #ccc;
  border-radius: 0.25rem;
}
</style>