Getting Eventful with JavaScript Events!

Natasha Avancini
3 min readMar 15, 2021

Anyone who uses the internet, in some form or another, has utilized Javascript. Things like the Amazon search bar, refreshing a Twitter feed, an embedded video on your favorite news site — the sheer amount of interactivity is pretty much limitless. Any dev wishing to improve user experience on a web page understands the need to incorporate JS into their apps, which is why I’ve decided to do a small deep dive into JS Events!

So, Why Events?

An event is simply an interaction that has a cause and effect. You click on something, and something else happens. Events!
The thing I’ve found most important while working on my Javascript app is asking myself these three questions:
— When: When should the event trigger?
— Cause: What will be the reason for the triggered event? (Button click, mouse over)
— Effect: What happens after the event?
Even if it is something as simple as creating a like button, those three questions are vital to making Javascript Events work. You master these, you’re golden.

Where To Start?

Beginning with our first question, “When?”, really depends on what you’re trying to accomplish. In the case of my app (a choose your own adventure game), I wanted to add a dice roll function that would decide if my users would win or lose a particular battle.
So in this instance, since it’s a CYOA, I want the event to trigger after the user has made the choice to battle.

The first thing I’ll want to do is create the template:

Here I’m calling the onclick on my button as a way to render the next portion of my event — which will also be the cause and effect.

The next function will be calling on the rollDie() logic above which will determine if the user wins or loses.

So, when a user clicks on the button, it’ll run the logic associated with the rollDisplay() function, and pop out whether the user has won or lost depending on the number that was rolled.

From there, my user can continue the story and hopefully make it to the end with many more wins beneath their belt.
In some cases, you’ll find that your when and cause will be redundant, but it’s still important to ask yourself those questions to help the flow of events.

Hopefully this helps anyone is might be having a bit of trouble with JS!

--

--

Natasha Avancini
0 Followers

Lentil soup devouring, casual game playing, one pup loving