DEV Community

Cover image for Why learning about Event Listeners & APIs in Javascript will only excite new upcoming developers
Anthony Rodriguez
Anthony Rodriguez

Posted on

Why learning about Event Listeners & APIs in Javascript will only excite new upcoming developers

Ever since I started my undergrad to become a chemical engineer, software development has always been on the forefront of my interests and passions. Using software such as MATLAB and VBA to solve complex differential equations only sparked and accelerated my growing interest in programming. I was intrigued on how programming can make a remarkably difficult task such a simple and painless process.

Image description

A few years after graduation, I decided to embark on a journey to pursue my passion for programming and transition into tech. Now that I am at flatiron school, I now have the structure and support to continue on this endeavor and finally make my vision come true. With that being said, it all starts with JavaScript and the fundamentals.

I don’t know about you, but the more I dive deep into a programming language, the more excited I become. This is especially true when it comes to learning about event listeners and APIs. These two topics completely changed the way I thought about programming. The three pillars of web-programming I've been reading about were finally making sense.

1. Recognize Events
2. Manipulate the DOM
3. Communicate with the Server
Enter fullscreen mode Exit fullscreen mode

I’ve always wondered about the intricacy of webpages and how the interaction and dynamics worked with the user. The simple act of clicking the like button on Instagram or retrieving data from public servers had intrigued me enough to start looking behind the scenes.

Image description

Only after learning about JavaScript event listeners and API GET/Fetch requests did I barely start to understand how webpages interacted with the user. Now that I’ve been through phase 1 of my program, I now see technology and the internet through a completely different lens. The internet, webpage applications, apps on your phone, TVs, calculators, cars, Tesla’s autopilot system, NASA’s rocket guidance system, video games, and just about every aspect of our lives is affected in some shape, way, or form due to programming. When I see an electronic display inside a new car, I can't help but to think about coding and the work it took to make that happen. When I check my bank account balance on my mobile app, I can only think about the programming required to make such events possible. Therefore, as new developer, event listeners and APIs are concepts that will get you to think about programming in a very different way.

Here in this blog, I will go over a very simple click event and additionally show how to extract data from an API. Hopefully for a beginner, learning about these concepts will further peak your interest and motivate you to learn a new programming language.

Adding Event Listeners In Javascript

Starting with a simple click event listener, JavaScript has a built-in method called .addEventListener() with the following arguments:

addEventListener(event, function, useCapture)
Enter fullscreen mode Exit fullscreen mode

This method generally takes in the first two arguments, the third useCapture argument is optional. The first argument refers to the type of event you want to perform. The event can be a click, mouseover, submit, keypress, or any other endless options that one can choose from. Here is a list of all DOM event handlers that we can choose from. Today, we will go with a simple 'click' event. The second argument, however, involves inserting a function that is eventually called upon when the event fires off, in our case clicking on a button. Assuming we have our basic HTML and Javascript file ready to go, we can start by first assigning the button tag from our HTML file to a variable called heartButton through the provided id.

 <button id='heart' > ❤️ </button> // From HTML File 
Enter fullscreen mode Exit fullscreen mode
const heartButton = document.querySelector('#heart') // From JS
Enter fullscreen mode Exit fullscreen mode

With the button tag now assigned to a variable, we can start creating a function that will activate once the heart button is clicked. To simplify the process, we can add an alert message once the button is clicked. The function is:

function myFunction (e) {
    e.preventDefault()
    alert('Thank you for the like!')
}
Enter fullscreen mode Exit fullscreen mode

When the like button is clicked, myFunction will fire and a pop-up box will appear with the message Thank you for the like!. Event handlers can be used in any number of endless ways. It's really only up to your imagination and creativity.

Now that the function has been created, we can then add and event like so:

heartButton.addEventListener('click', myFunction)
Enter fullscreen mode Exit fullscreen mode

Combining our JS code with our HTML file, we now a complete and functional button event listener! The animation below shows how the event looks like when the button is clicked and activated.

Image description

APIs and Fetch Requests

Application programming interfaces (or APIs) is the next awe moment I've had while learning the fundamentals of Javascript. While not going too much into detail, APIs allow a safe exchange of data between clients and a servers defined by specific set of rules and protocols. You can think of it as an online data server that we can extract data from and use for our own applications and projects. For example, have you ever wondered how on some websites, users are able to use Google Maps within the website as a tool for various situations (e.g. Shipley Donut's website showing locations of their stores on a Google Map). That's Google's APIs at work! For instance, many popular hiking trail apps use Google Maps APIs to displays trails and routes for their users to see. This can really come in handy if you don't want to make your own maps from scratch. It is also important to say that usually each API has its own API documentation explaining how developers should structure the requests and responses of their data. Enough talking, let's start coding.

To gain access to public APIs in Javascript, the general syntax is as follows:

fetch(url)
.then(response=>response.json())
.then(data=>console.log(data))

Enter fullscreen mode Exit fullscreen mode

APIs can get very deep and technical, however, for the purposes of this blog I will keep it to a minimum. If you want dive deep into APIs you can learn more about it here.

The fetch(url) is where API data is technically located. Each API documentation will state specifically how to access certain data objects. Think about fetch as a request to gain access to a data server. Once the server recognizes the request, the server then shoots back a response promise. This response is basically stating "I have your data here, however, you have to convert it to a readable format". This is where response.json() comes and saves the day. This part of our code converts the data in promise to a readable format so that we can then have complete access to that information. Lastly, .then(data=>console.log(data)) is where the fun begins. This last piece of code is where we can manipulate the data to our liking with the access from our fetch request.

For my Phase 1 assessment project, I used an art museum API to display art museum paintings accessed through the 'Art Institute of Chicago' website. I followed their API documentation to access their data by using their 'search' endpoint url and by manually adding the number of images I wanted my webpage to display. The following fetch snippet comes directly from my phase 1 project:

function fetchArt(inputText, trueNum) {
    fetch(`https://api.artic.edu/api/v1/artworks/search?q=${inputText}&limit=${trueNum}`)
    .then(resp=>resp.json())
    .then(dataTotal=>{
    // We can now code here // 
        dataTotal.data.forEach(loadDom)
        })
    .catch((error)=>console.error('There was an error with Fetch!', error))

Enter fullscreen mode Exit fullscreen mode

Once we received our promise in .json format, only then can we start using the data available to our liking. Data sent from the server can look something like the following:

Image description

Finally, to drive the point home, the animation below shows how my project receives the API. Make sure to pay close attention to the console log on the browser. This will show the API data objects and attributes I have access to.

Image description

Wow! That was a read wasn't it? If you are anything like me, these two simple Javascript concepts really revolutionized the way I think about webpages and programming in general. The concept of how data is used, along with how the user dynamically interacts with the website, really put things into perspective for me. Every programming language is different with their positives and negatives, however, they are all the same at their core; instructing (i.e. programming) a computer to do specific a thing or task. I hope this blog gives a junior developer, or someone interested in learning a new programming language, a short insight into how programming can be really exciting. The road can be a difficult and challenging one, but exciting nonetheless.

Top comments (2)

Collapse
 
dobby_cesi profile image
Cesilia Pereira

I created my own payroll program using QBasic many years ago. It is interesting how things have evolved. Great article!

Collapse
 
karina_henriquez_a03ab296 profile image
Karina Henriquez

Very interesting and informative article!