Frontend Masters Boost RSS Feed https://frontendmasters.com/blog Helping Your Journey to Senior Developer Fri, 19 Jan 2024 00:16:40 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.2 225069128 Dispatching an Event https://frontendmasters.com/blog/dispatching-an-event/ https://frontendmasters.com/blog/dispatching-an-event/#comments Wed, 17 Jan 2024 21:31:38 +0000 https://frontendmasters.com/blog/?p=540 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">

<output>
  Characters: <span></span>
</output>
const input = document.querySelector("input");
const output = document.querySelector("output > span");

input.addEventListener("input", () => {
  output.innerHTML = input.value.length;
});

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:

input.dispatchEvent(
  new Event("input", {
    bubbles: true,
    cancelable: true
  })
);

Works!

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!

]]>
https://frontendmasters.com/blog/dispatching-an-event/feed/ 2 540