Monday 12 January 2015

Advantages of using JQuery callback function.



jquery
It sometime happens that you write code x, y, z on line number 1, 2 and 3. Now x is not yet finished while y and then z started running. This can creates a serious problem when x need to be finished before y or z started. This problem can be solved using call back function. I will here demonstrate a program in jquery where I will show function called with and without call back function.

This code is with call back function

$("#btn1").click(function() {
  $("#divText").text(function() {
    alert('Div text element set with Call back function');
    return "This click is with callback function";
  });
});


Here as you can see the alert message is popped up before the div text is set. But if we have done it without call back function like this...

$("#btn1").click(function() {
  $("#divText").text("This click is with callback function");
    alert('Div text element set with Call back function');
});


then div text have been set first then alert message is popped up.

 Here is the full program

<html>
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$("document").ready(function() {
$("#btn1").click(function() {
  $("#divText").text("This click is with callback function");
  alert("Div text element set with Call back function"); 
});


$("#btn2").click(function() {
  $("#divText").text("This click is with callback function");
    alert('Div text element set with Call back function');
});

 });
</script>
</head>
<body>
<input type="button" id="btn1" value="Click Me" /><br>
<br><input type="button" id="btn2" value="Click Me" /><div id="divText">
</div>
</body>
</html>





No comments: