DEV Community

Cover image for JavaScript syntax: event listeners
Brittan Fairchild
Brittan Fairchild

Posted on

JavaScript syntax: event listeners

People learn in a wide range of different ways. The easiest and most logical path to one person might seem a confusing puzzle to another. Luckily for the coding community, the code that we write can be varied and flexible. I stumbled across a great example of this in a recent JavaScript lesson regarding event listeners that were added to buttons.

To add an event listener to a button is simple. We can write it as such:

Alt Text

In this example, whenever the "click" event happens to our designated button, the function "myFunction()" will fire. You can then go on to write out what that function will do when it is triggered. This approach is what was introduced to me at first, but then my instructor showed me a different way to do things that made much more sense to me.

Alt Text

In this example, I add my event listener to my button by appending ".onclick" to the variable that I have designated for the button itself. By then calling my event, "e", I use an arrow function to dive into what function the button will have once it's clicked without stopping to define another function.

Both of these examples accomplish the same thing, and both function as intended. Some of my classmates preferred one way over the other. What I have come to love about coding the most is that there are a near limitless ways to go about finding a solution to a problem. Some might be more cumbersome and convoluted than others. Some might be far cleaner and utilize fewer lines of code. Each of us will have our own styles and ways of navigating through problems. Every path taken will be correct, as long as the solution is achieved.

Alt Text

Latest comments (0)