Callback Function in JavaScript(DOM Manipulation using callback function)

DENNIS ILUMA
1 min readJul 18, 2021

--

In JS, a callback function is a function that is passed into another function or method as an argument. A callback function is not automatically called. It is called when required. When using a callback function, her parentheses are removed. If the parentheses are added,the function will be automatically called. E.g

An Example below is a simple DOM Manipulation using callback function

Create a script file in your html document or an external JavaScript file and add the below code on it.

/* get the first h1 element from our html document page and save it as firstTitleElement */const firstTitleElement = document.querySelector(‘h1’);/* create a callback function that will change the background color of the first h1 element when the user click on it */function exampleCallBackFunction(){
firstTitleElement.style.background = 'blue';
}
/* now set an event listener that will call the exampleCallBackFunction when the user click on the h1 element*/firstTitleElement.addEventListener('click',exampleCallBackFunction);/* NOTE: when we used the callback function, we didn't add parenthesis to it like this exampleCallBackFunction(). If we had added parenthesis to it, the background colour would have changed to blue before we attempt clicking on the element */

--

--

DENNIS ILUMA
DENNIS ILUMA

Written by DENNIS ILUMA

0 Followers

Software engineer. Majors in Java, AI, Frontend, DevOps & Cloud.

No responses yet