Dispatching an Event

Sometimes when crafting up some quick interactive vanilla JavaScript, I add an event listener and write the functionality I want to happen right there. For example, here’s a super basic character counter:

<input type="text">

  Characters: <span></span>
</output>Code language: HTML, XML (xml)
const input = document.querySelector("input");
const output = document.querySelector("output > span");

input.addEventListener("input", () => {
  output.innerHTML = input.value.length;
});Code language: JavaScript (javascript)

Totally works. But, you won’t see any character count until you start typing something. That’s probably not ideal. It should count the characters when this HTML initially loads.

So how do you fire off an initial count? One way is to shoot a “synthetic” event at the input, so that event hander fires. That’s right, you can just create an event out of thin air with code and dispatch it. Like:

  new Event("input", {
    bubbles: true,
    cancelable: true
);Code language: JavaScript (javascript)


That’s not the only way do this. We could make the event handler call a function (instead of using an anonymous function) and then just call that function once ourselves. That’s probably, generally, a more sane way to go about it. But it’s good to know multiple ways. Plus, some event handler functions use the event as a parameter to do things, and rather than write logical conditions on the presence of that event, providing the synthetic one makes that easier.

Lots more to learn on the JavaScript Learning Path!

It's time to take your JavaScript to the next level

Frontend Masters logo

Frontend Masters is the best place on the web to really learn JavaScript. We have a complete learning path from the biggest and best teachers in JavaScript to help you make the most out of the web's biggest language.

2 responses to “Dispatching an Event”

  1. Avatar Shum Stra says:

    In this situation, we could also store the event listener as a constant and run it manually initially:

    Passing functions around as values has increasingly become my jam.

    If our event listener made use of the event argument passed to it, you would still need to create an Event object and in that case it just might be easier and cleaner to dispatch an event manually.

    (btw, thank you for all you do, Chris! 😃)

  2. Avatar Alec says:

    My thinking was just to put 0 in the span tag. Just don’t do anything clever like initialising the input with a value, OK?

Leave a Reply

Your email address will not be published. Required fields are marked *