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>
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:
input.dispatchEvent(
new Event("input", {
bubbles: true,
cancelable: true
})
);
Code language: JavaScript (javascript)
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!
In this situation, we could also store the event listener as a constant and run it manually initially:
https://codepen.io/shumstra/pen/LYaWovv
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! 😃)
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?