3 min read

How to use Vanilla JavaScript to listen for and emit events

How to use Vanilla JavaScript to listen for and emit events

Today I'll teach you how to listen for and emit events using only JavaScript and the DOM. If you are a Web Developer, you may be aware that everything begins with events, such as moving, clicking, and keying, but how about developing your own events to perform your tasks?

Fire a click event

We can emit a click event at any place in the front-end context; let's create a basic page to demonstrate this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Fire a click event</title>
  </head>
  <body>
    <button id="button">Click to subscribe, please! ๐Ÿ™ (<span>0</span>)</button>
    <script lang="javascript" async>
      const buttonElement = document.getElementById("button")
      let counter = 0

      buttonElement.addEventListener('click', function (event) {
          event.preventDefault()
          counter++
          const counterElement = this.getElementsByTagName("span")[0]
          counterElement.innerText = counter.toString()
      })

      setInterval(() => {
        buttonElement.dispatchEvent(new Event('click'))
      }, 5000)
    </script>
  </body>
</html>
Take a deep breath, Angular, React, and Vue devs, and remember that this is pure and portable Vanilla. Keep cool and relax, I know you like writing your effects, directives, and states. ๐Ÿค—

In the following example, we have a basic website that forces a person to click against their will, similar to how some ads work ๐Ÿค‘.

  • addEventListener, adds a function to listen for element events;
  • dispatchEvent, send an event to an element; if the element is not listening, the event is omitted;

Following that is a screencast of how this example works:

Why not create your own events?

We may add an event to a web application, such as a logout event, redirect event, push event, or anything else important to your application or website. If you would like to combine different libraries, you may use DOM power events to accomplish so.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Document events</title>
  </head>
  <body>
    <button id="button">Purge Session ๐Ÿงน</button>
    <script lang="javascript" async>
      document.addEventListener('logout', function () {
        sessionStorage.clear()
        localStorage.clear()

        console.log('Your session has been deleted...')

        document.bgColor = 'tomato'

        setTimeout(() => {
          document.bgColor = '#fff'
        }, 2000)
      })

      const buttonElement = document.getElementById("button")

      buttonElement.addEventListener('click', function (event) {
        event.preventDefault()
        document.dispatchEvent(new Event('logout'))
      })
    </script>
  </body>
</html>

The first time we received an alert box, next messages were sent to the console since the alert function was no longer listening.

Removing an event

Using the following function, we can remove a registered event:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>RemoveEventListener in action</title>
  </head>
  <body>
    <button id="button">Click one time</button>
    <script lang="javascript" async>
      const buttonElement = document.getElementById('button')
      let counter = 0

      function handleClickAlert(event) {
        event.preventDefault()
        alert('click works!')
        buttonElement.removeEventListener('click', handleClickAlert, false)
      }

      function handleClickSilent(event) {
        event.preventDefault()

        counter++
        console.log(`click works ${counter}!`)
      }

      buttonElement.addEventListener('click', handleClickSilent)
      buttonElement.addEventListener('click', handleClickAlert)
    </script>
  </body>
</html>

Because we can add multiple listeners, we must specify which function should be removed. The first time we received an alert box, next messages were sent to the console since the alert function was no longer listening.

That's all

Previous examples is designed to works with the most recent browser; if you use Internet Explorer 6, something may not work properly. ๐Ÿคญ

Sometimes DOM Events are all we need to integrate things; multiple frameworks handle the work of listening for and emitting events, but it's crucial to understand how things function without the library and packages. That is my only objective in writing this post.

Keep your kernel ๐Ÿง  up to date. God's ๐Ÿ™๐Ÿฟ blessings on you.