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>
setTimeout()
and setInterval()
.<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>
<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>
<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>
<img src="image.jpg" usemap="#map1"> <map name="map1"> <area shape="rect" coords="9, 120, 56, 149" href="#"> <area shape="rect" coords="100, 200, 156, 249" href="#"> </map>
#id { overflow: auto; }
document.getElementById("id").onmouseover = function(){ document.write("Have Good Life"); }
if(isset($_GET["id"])) { echo $_GET["id"]; }