DEV Community

Cover image for Callback Functions
Tate Braeckel
Tate Braeckel

Posted on

Callback Functions

"A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action."
-https://developer.mozilla.org/en-US/docs/Glossary/Callback_function

Callback functions are an essential tool in modern web development used in both synchronous and asynchronous execution. Callback functions are used most commonly in asynchronous code execution, especially in response to an event, like a 'click' event or 'mouseover' event.

Below is a simple example of how I used a callback function in my phase 1 final project:

document.getElementById('cutie').addEventListener("onmouseover", hideKitty);

function hideKitty() {
    document.getElementById("cutie").style.display = 'none';
}
Enter fullscreen mode Exit fullscreen mode

First I used the 'getElementById' method to grab an html element from my html file called 'cutie'. This happened to be an element which the user would see on the client side. Once I grabbed the image I used 'addEventListener' as a function/ method to attach an event listener to the element.

AddEventListener needs two arguments, the event type and a callback function. Mine is using an 'onmouseover' event type, meaning the user only needs to swipe the mouse over this image to invoke the function. Once the mouse over is initiated, it uses the callback function in the second argument- which in this case is hideKitty().

Now that the event fired and invoked the "hideKitty" function, the code block inside of hideKitty executes. Again I used the getElementById()method to grab the image - I realize now I could have assigned a variable to this element in the global scope, but did not in this case a kept grabbing it in each code block.

Using dot notation I used style.display to change how the image was displayed by assigning it a value of 'none'. So the image 'disappears' when the event fires and executes the callback of hideKitty. The 'showKitty' function uses a setTimeout() method to show the image again after 3000 milliseconds.

Another example in my code of a callback function is in here:

const fetchBtn = document.querySelector('#btnGet');
fetchBtn.addEventListener('click', getMovies);

function getMovies() {
    fetch(`http://localhost:3000/movies`)
        .then((response) => response.json())
        .then((data) => {
            let result = document.getElementById('result');

            result.innerText = '';

            data.forEach((movie) => {
                result.innerHTML +=
                    `<p class="movieItem" >${movie.title} is a(n) ${movie.genre} movie that was released in ${movie.release}</p>`
            })
        })
}
Enter fullscreen mode Exit fullscreen mode

After capturing the button 'btnGet' with a querySelector, I added an eventListener() method, which takes in two arguments: the string of the event, such as 'click' and a callback function. In this case, I have my function getMovies as the callback in the eventListener. Once the click event is fired, it asynchronously executes the getMovies function and the code block within. In this case, it is a fetch GET request on a db.json local server that contains movie objects in the array.

So once the 'click' event happens, the getMovies function is executed. The fetch GET request begins it's process. Reference to the break down of this fetch GET request is here.

Top comments (0)