Using callback functions

Callback Functions are functions that are passed as arguments to other function.

- Example (see the comments in code):
<p>When the following button is clicked, it is added its tag-name in #resp</p>
<button id='btn'>Click</button>
<blockquote id='resp'>#resp</blockquote>
<script>
// defines a callback function, receives an object with the event
function callback(ev){
 //adds in #resp the name of the html element that emitted the event
 document.getElementById('resp').innerHTML = ev.target.tagName;
}

// registers the click event on #btn to call the callback() function
document.getElementById('btn').addEventListener('click', callback);
</script>
• There are JavaScript functions that can be used only with callback function. For example: setTimeout() and setInterval().
Example, displays the number of seconds into a HTML element. Test yourself this example.
<ht>Example callback function with setInterval()</h4>
<blockquote id='resp'>#resp</blockquote>
<script>
var seconds = 0;
var resp = document.getElementById('resp');

// used as callback function in setInterval()
function addSeconds(x) {
 // increments the seconds and adds the value in #resp
 seconds++;
 resp.innerHTML = seconds;
}

// calls the addSeconds() to every second (1000 milliseconds)
setInterval('addSeconds()', 1000);
</script>
• Anonymous functions can also be used as callback functions.
- Here is an example with setTimeout() and an anonymous arrow function used as argument.
<ht>Example anonymous function with setTimeout()</h4>
<blockquote id='resp'>#resp</blockquote>
<script>
var resp = document.getElementById('resp');

//adds a text in #resp after 2 seconds
setTimeout(()=>{
 resp.innerHTML ='https://CoursesWeb.net/';
}, 2000);
</script>
The callback function can be very useful when we want to finish a long task, while allowing us to continue the execution of the JavaScript code.
- A good example is with an Ajax function that receives a callback function as argument. When the server response is completely received, it is passed to the callback function, but in the meen time the script continues to preccess the other instructions.
- If you want to test this example, you have to create a text file, named 'test.txt', with some text, in the same folder in which you have the page with this script.
<script>
// gets data from external file
// receives the URL address of the file, and a callback function that will be called when the response is received
function ajaxF(url, callback) {
 var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); // sets the XMLHttpRequest instance

 request.open('GET', url); // define the request
 request.send(null); // sends data

 // Check request status, when the response is completely received pass it to callback function
 request.onreadystatechange = function() {
 if (request.readyState == 4) {
 callback(request.responseText);
 }
 }
}

// the callback function
function addResp(resp) {
 alert(resp);
}

// calls the ajaxF() function, passing the file address, and the callback function
ajaxF('test.txt', addResp);

// continue the script while the Ajax and callback functions are executed
alert('Message 1');
</script>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Click on the HTML tag which creates an horizontal line in web page.
<br /> <em> <hr />
Some content ...
<hr />
Content under line ...
Which CSS property defines the text color?
font-style font-variant color
h2 {
  color: #cbdafb;
}
Click on the function which searches if a character, or text exists in a string.
indexOf() toString() split()
var str = "Web courses - http://CoursesWeb.net/";
if(str.indexOf("http://") == -1) alert("http:// isn`t in string");
else alert("http:// is in string");
Which function splits a string into an array of strings based on a separator?
array_merge() explode() implode()
$str = "apple,banana,melon,pear";
$arr = explode(",", $str);
var_export($arr);      // array (0=>"apple", 1=>"banana", 2=>"melon", 3=>"pear")
Callback Functions in JavaScript

Last accessed pages

  1. Input text fields (2285)
  2. Insert, Select and Update NULL value in MySQL (30219)
  3. Register and show online users and visitors (25571)
  4. JavaScript Slideshow Content (855)
  5. Get Attribute (ID, Class, Name, Title, Src) with jQuery (55241)

Popular pages this month

  1. Insert, Select and Update NULL value in MySQL (515)
  2. Read Excel file data in PHP - PhpExcelReader (430)
  3. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (319)
  4. PHP getElementById and getElementsByTagName (255)
  5. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (234)