Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

javascript: typeerror (intermediate value) is not a constructor

It's been long time since i have written a blog post as i am busy with the project deliverable. So, here i am with one more issue which i faced today while writing some basic javascript code.

The error is 

javascript: typeerror (intermediate value) is not a constructor

i came across this issue when i am returning some object from a function. Following is the similar javascript code that i have written

function buildContact() {
        return new { name: "John", mobile: "123-456-7890", country: "US" };
    } 

this is the javascript function which was showing the mentioned error. 

Cause:

I used new which can be only used with a Function as operand. In this case i am using object as a constructor which is actually not. 

Fix:

Here we have two options to fix this error. 

1. To return object directly as shown below
function buildContact() {
        return { name: "John", mobile: "123-456-7890", country: "US" };
    }      

2. Create a constructor and use the constructor to create new object as shown below

function Contact(name, mobile, country) {
        this.name = name;
        this.mobile = mobile;
        this.country = country;
    }

    function buildContact() {
        return new Contact("John", "123-456-7890", "US");
    }

in this case we are returning the new Contact() by using constructor. 

In this way you can fix the error javascript: typeerror (intermediate value) is not a constructor.

Please do comment if you know better way to fix this error. Thanks in advance. 

To know more common javascript errors visit: Javascript 


Read more...

How to make Ajax call with JQuery

In this article am going to explain how to make ajax call with JQuery.

JQuery has $.ajax() method which is used to perform an asynchronous HTTP request.

The syntax of $.ajax() function is as follows

$.ajax(url[, options])

url is a string parameter that you want to reach with AJAX call while options is an object literal containing the configuration for the Ajax request.

JQuery AJAX example:

$.ajax({
  url: "demo.txt",
  success: function(result){
    alert(result);
  }
});

JQuery AJAX post example:

$.ajax({
  type: "POST",
  url: url,
  data: {name:"ranadheer",id:2},
  success: function(data, status,, jQxhr){
     alert(data);
  },
  error: function(jQxhr, textStatus){
     alert(error);
  }
  dataType: dataType
});


This way we can make AJAX calls with JQuery.

For more posts on JQuery visit: JQuery

Read more...

Create cookie using JQuery

This article explains how to create/read/edit/delete cookie in Jquery.

First you need to add jquery cookie plugin. Add jquery.cookie.js javascript file from following url.

https://github.com/carhartl/jquery-cookie/blob/master/src/jquery.cookie.js

Create/Set cookie using JQuery:

Use the following jquery code to create the cookie.

 $.cookie("cookieName", "cookieValue");

Use the following jquery code to create the cookie with expiry.

$.cookie("cookieName", "cookieValue", { expires: 7 });

above cookie expires in 7 days.


Get/Read cookie using JQuery:

Use the following jquery code to read the cookie value.


$.cookie("cookieName");

We just have to use the cookie name to read it's value.


Edit cookie value using JQuery:

Use the following jquery code to edit the cookie value.

$.cookie("existingCookieName", "newValue");

above code updates the existing cookie value.


Delete cookie using JQuery:

Use the following jquery code to delete the cookie

$.removeCookie("cookieNameToBeRemoved");

In this way we can create/get/edit and delete cookies using JQuery.

For more posts on JQuery visit: JQuery


Read more...

Convert string to boolean in javascript

In this article i am going to explain how to Convert string to Boolean in JavaScript.

There is no built-in function in JavaScript to Convert a string to Boolean.

Be careful when using following method in JavaScript.

var boolValue = Boolean("true");

The above Boolean() method, any string which is not empty will be evaluated to true.

All the following statements return true using Boolean() function in JavaScript.

var boolValue = Boolean('true');   // true
var boolValue = Boolean('false');  //true
var boolValue = Boolean('someOtherString');  //true


So, only easy and trusted way to Convert a string to Boolean in JavaScript is by checking string value manually.

Example:
var myString = 'true';

var boolValue = (myString == 'true');

Above statement returns true if myString value is equal to 'true', other wise it returns false.   

For live example visit the following JSFiddle : Convert string to boolean in javascript

In this way we can Convert a string to Boolean in JavaScript.

please leave comment for any queries or suggestions.

For more posts on JavaScript visit: JavaScript

Read more...

How to redirect a page using JavaScript or JQuery

In this article i am going to explain how to redirect a page using javaScript or JQuery.

It is better to use JavaScript to redirect a page than using JQuery as JavaScript is simple compared to JQuery.

Example:

You can use any of the following code to redirect a page using JavaScript

// similar behavior as an HTTP redirect
window.location.replace("http://yourdomain.com");

// similar behavior as clicking on a link
window.location.href = "http://yourdomain.com";

Both lines mentioned above redirects the page to location given in parenthesis. Only difference is window.locaiton.replace does not put the new page in session history. That means once you redirected to new page then you will not be able to go back to old page using browser's back button.

Where as if you use window.location.href new page will be stored in the session so that you can be able to go back to old page using browser's back button.

I have added an example in JSFiddle. You can check in this link Redirect page using JavaScript


Redirect page using JQuery


Use the following code to redirect a page using JQuery

$(location).attr('href', 'http://yourDomain.com')

In this way you can redirect a page using JavaScript or JQuery.


For more posts on JavaScript visit JavaScript


For more posts on JQuery visit JQuery

Read more...

Create table dynamically using JavaScript

In this article i am going to show you How to create a table dynamically using JavaScript

Consider you have following html

<html>
 <body>
   <div id="table-container">
   
   </div>
 </body>
</html>

Now you can create table dynamically using following JavaScript

  var table  = document.createElement("table");             // creating table dynamically
  var tableBody= document.createElement("tbody");      // creating table body dynamically
  var row = document.createElement("tr");                      // creating table row dynamically
  var cell1 = document.createElement("td");                    // creating table cell dynamically
  cell1.innerHTML = "Name";


// append cell to row. (you can create any number of cells and then append to row)
row.appendChild(cell1);

// append row to table body
tableBody.appendChild(row);

// finally append table body to table
table.appendChild(tableBody);

So, by above JavaScript code we have created a table dynamically.

Now let's append the dynamically created table to div.

  var container = document.getElementById("table-container");
  container.appendChild(table);

We added dynamically created table to container.

In this way we can create a table dynamically using Javascript

Also check : Create table dynamically using JQuery

Read more...

Dynamically add or delete rows to table using Javascript

In this article i am going to show you How to dynamically add or remove(delete) rows from table using Javascript

Consider you have following html

<html>
 <body>
   <div id="table-container">
       <table id="my-table">
       </table>
   </div>
 </body>
</html>

We already have a table with id = "my-table"

Now, let's see how to add rows dynamically using Javascript


first let's create rows

  var row1 = table.insertRow(0);

Above command creates an empty <tr> element and adds it to the first position of the table

  var row2 = table.insertRow(1); 

Above command creates an empty <tr> element and adds it to the second position of the table

Now, let's create row cells

 var cell1 = row1.insertCell(0);
 cell1.innerHTML = "Name";

Above command creates an empty cell and adds it to first row of the table

 var cell2 = document.createElement("td");
 cell2.innerHTML = "Age";

Above command creates an empty cell and adds it to first row of the table.

Now we have a table with two rows and first row having two cells.


Remove rows dynamically using Javascript


  document.getElementById("my-table").deleteRow(0);

Above command deletes first row from the table having id = "my-table"

In this way we can dynamically add or delete rows from table dynamically JavaScript

Also check - Create table dynamically using JQuery

Read more...

Checkbox checked property in JQuery

Using JQuery we can check whether a checkbox is checked or not.

Consider you have a check box like below

<input type="checkbox" id="checkbox1"/>

 Using the below JQuery code, you can check whether the above checkbox is checked or not


if ($("#checkbox1").is(':checked')) {
    alert("checked");  // checked
}
else {
    alert("not checked"); // unchecked 
}

Note: is(':checked') returns TRUE if the checkbox is checked else it returns false.

You can also use below code to check checkbox is checked:


if ($("#checkbox1").attr("checked")) {
    alert("Checked");
}
else {
    alert("Unchecked");
}

Note: Since jQuery 1.6, The behavior ofjQuery.attr() has changed. So it is recommended not to use it.

Javascript Code to check checkbox's checked property:


var myCheckbox = document.getElementById('checkbox1');
 
myCheckbox.onchange = function () {
    if (this.checked) {
        alert("checked");
    }
    else {
        alert("not checked");
    }
}

In this way you can check whether a checkbox is checked ot not using JQuery

For more posts on JQuery please visit: JQuery

Read more...

Truncate Filter for AngularJS

You can truncate the text using angularJS by creating a truncate filter. The truncate filter accepts inputs like text to truncate,maximum length of the text allowed and truncating characters to append to the text (like '...')

Truncate Filter:


Add the following filter in your javascript file.

angular.module('filters', []).
filter('truncate'function () {
    return function (text, length, end) {
        if (isNaN(length))
            length = 10;
 
        if (end === undefined)
            end = "...";
 
        if (text.length <= length || text.length - end.length <= length) {
            return text;
        }
        else {
            return String(text).substring(0, length - end.length) + end;
        }
 
    };
});
Now use the truncate filter in your html code like below

<div id="main">
        <p>{{yourTextHere|truncate}}</p>  /*case:1*/
        <p>{{yourTextHere|truncate:5}}</p> /*case:2*/
        <p>{{yourTextHere|truncate:25:" ->"}}</p> /*case:3*/
</div>

In case 1, we are just using filter and not mentioning any length. So as defined in the filter code, the default length will be taken (10 in our case).

In case 2, we are providing length. So filter will limit the text as per the length mentioned.

In case 3, we are providing length and end. So filter uses this length to truncate the text and appends the given symbol at the end of the truncated text.

In this way we can truncate the text using AngularJS truncate filter.

For more posts on angularJS visit: angularJS



Read more...

How to open hyperlink in new window

We can open hyperlink in new window using javascript.

lets consider you have the following hyperlink

<a class="link" onclick="openWindow();"> open me in new window </a>
As we are not using href attribute above hyperlink is shown as plain text. So use below styles to make it look as a hyperlink

.link {
    colorblue;
    cursorpointer;
}

Now add the following javascript code

function openWindow() {
    window.open('http://coding-issues.com''''width=950,height=700');
}

The above javascript opens the new window when you click on the hyperlink.

Note: You have to specify the height and width of the new window. Otherwise it opens a new tab instead of new window.

Demo:

open me in new window


In this way we can open the hyperlink in new window using javascript.

For more posts on Javascript visit: javascript

Read more...

How to disable or enable input field using JQuery

If you want to disable any input field like button or checkbox or textbox etc, you can do it using JQuery.

Consider you have the following input fields in your page

<input type="text" id="tb1" />
<input type="button" id="btn1" />
<input type="checkbox" id="chkbx1" />
<input type="radio" id="radio1" />
Now if you don't want to allow a user to enter text into textbox(in cases when you are showing pre-loaded data) or if you don't want to allow a user to click on the submit/send button until all the form fields are valid, then in the above cases you can disable those input fileds using jQuery's prop() method.

jQuery code to disable the input fields:


Disable textbox using jQuery


$("#tb1").prop('disabled'true);  //for jQuery 1.6+
$("#tb1").attr('disabled''disabled'); //for jQuery 1.5 and below

Re-enable textbox using jQuery


$("#tb1").prop('disabled'false); //for jQuery 1.6+
$("#tb1").removeAttr('disabled'); //for jQuery 1.5 and below

Disable button using jQuery


$("#btn1").prop('disabled'true);  //for jQuery 1.6+
$("#btn1").attr('disabled''disabled'); //for jQuery 1.5 and below

Re-enable button using jQuery


$("#btn1").prop('disabled'false); //for jQuery 1.6+
$("#btn1").removeAttr('disabled'); //for jQuery 1.5 and below

You can also disable radio button or checkbox using jQuery in the same way.

In this way you can disable the input fields using jQuery. Let me no if it helped you through comments section. Feel free to share any information.

For more posts on jQuery please visit: jQuery

Read more...

get current window url in javascript

You can get the url of the current window using javascript.

To get the current window url, use the below javascript:

var url = window.location.href;
The above javascript code gives the full url of the window.


To get the current window url using jquery, use the below code:

var url = $(location).attr('href');


To get the origin of the url use the following javascript code:


var origin = window.location.origin;


To get the pathname use:


var pathname = window.location.pathname;


To get the current window protocol use:


var origin = window.location.protocol;


To get the port number of the current window use:


var port = window.location.port;


To Reload the current page using javascript use:


window.location.reload();


In this way you can get the url of the current window using javascript.

For more posts regaring please visit : Javascript


Read more...

Get Asp.Net TextBox or Label value using JavaScript

If you have a Asp.Net TextBox or Label then you can get the value of that textbox/label using javascript.

Get TextBox value:


Lets say you have a asp.net textbox like below

<asp:TextBox ID="txtName" runat="server" />

then you can get the value of the above textbox using javascript using the below code

var name = document.getElementById("<%=txtName.ClientID %>").value;

Get Label value :


Lets say you have a asp.net label like below

<asp:Label ID="lblName" runat="server" Text="codeSolver"/>

then you can get the value of the above label using javascript using the below code

var name = document.getElementById("<%=lblName.ClientID %>").innerHTML;

Note: If you notice the selector in the above code, we are using "ClientID" to get the value of the control. This is because Asp.Net controls are rendered as html controls in the browser. The "id" will be not same as what you have given to that control.

So if you simply write getElementById("txtName") it won't work. We use that syntax to get the value of a HTML input(type="text") element.

In this way we can get the Asp.Net TextBox or Label values using javascript.

For more posts on Javascript visit: javascript

Read more...

Check or Uncheck all checkboxes with master checkbox in jquery

In many sites you have seen this situation(example: in Gmail) where checking the master checkbox should check all the other child checkboxes or unchecking the master checkbox should uncheck all the other child checkboxes. So, in this post we are going to see how we can do this using JQuery.

Checking the all checkboxes when the header checkbox is checked


Lets create a group of checkboxes

<input type="checkbox" id="headerCheckbox"/>
 
    <input type="checkbox" class="childCheckBox" id="Checkbox1"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox2"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox3"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox4"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox5"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox6"/> 

We have created a header checkbox and some child checkboxes. We have used same class(class="childCheckBox") for all the child checkboxes which are related to the header checkbox. Now, if we check the header checkbox all the child checkboxes should be checked.

For that, use the below JQuery code

$('#headerCheckbox').click(function () {
    var isheaderChecked = this.checked;
    $(".childCheckBox").each(function () {
        this.checked = isChecked;
    })
})

The above code will check all checkboxes with the class "childCheckBox" and also if you uncheck the header checkbox then all the child checkboxes will be unchecked.

Unchecking the header checkbox when any one of the child checkbox is unchecked


When you uncheck any one of the child checkbox then the header checkbox should also be unchecked. For that case use the following JQuery code

$("input[type='checkbox']:not(:first)").click(function () {
    var allChecked = true;
    $("input[type='checkbox']:not(:first)").each(function () {
        if (this.checked == false) {
            allChecked = false;
            $('#headerCheckbox').prop('checked'false);
        }
    })
    if (allChecked == true) {
        $('#headerCheckbox').prop('checked'true);
    }
})

In this way you can check or uncheck all the checkboxes when a master checkbox is checked.

For more posts on Jquery please visit: JQuery

Read more...

How to Set/Get the textbox value using JQuery/Javascript

If you have a textbox, then you can get the value of the textbox or you can set the value of the textbox using JQuery.

Example:

Lets say you have a textbox like below

First Name:<input type="text" id="txtFirstName" />

JQuery code to get textbox value

var value=$('#txtFirstName').val();

Javascript code to get textbox value

var Firstname = document.getElementById('txtFirstName').value;

JQuery code to set textbox value

$('#txtFirstName').val("your name");

Javascript code to to set textbox value

document.getElementById('txtFirstName').value = "your name";

In this way you can set/get textbox value using jquery/javascript.

For more posts on Javascript/JQuery visit: jquery


Read more...

AngularJs directive for Image Cropping

Whenever we are allowing a user to upload images, it's better to provide cropping option for them. So, today we will discuss about the AngularJs directive which allows users to crop image before saving it.

For that you need to use JQuery's JCrop plugIn in your project. You can download it from https://github.com/tapmodo/Jcrop . Download the zip from the above link and add jquery.jcrop.js and jquery.jcrop.css files to your project.

<script src="scripts/jquery.min.js" type="text/javascript">
</script>
<script src="scripts/jquery.Jcrop.js" type="text/javascript">
</script>

<link href="css/jquery.Jcrop.css" rel="stylesheet" type="text/css">

Now add the following angularjs directive in your javascript file
app.directive('imgCropped'function () {
    return {
        restrict: 'E',
        replace: true,
        scope: { src: '@', selected: '&' },
        link: function (scope, element, attr) {
            var myImg;
            var clear = function () {
                if (myImg) {
                    myImg.next().remove();
                    myImg.remove();
                    myImg = undefined;
                }
            };
 
            scope.$watch('src'function (nv) {
                clear();
                if (nv) {
                    element.after('<img />');
                    myImg = element.next();
                    myImg.attr('src', nv);
                    $(myImg).Jcrop({
                        trackDocument: true,
                        onSelect: function (x) {
                            scope.$apply(function () {
                                scope.selected({ cords: x });
                            });
                        },
                        aspectRatio: 1
                    }, function () {
                        // Use the API to get the real image size 
                        var bounds = this.getBounds();
                        boundx = bounds[0];
                        boundy = bounds[1];
                    });
                }
            });
            scope.$on('$destroy', clear);
        }
    };
});

Now add the following html code in body section
<div ng-controller="MainCtrl">
    <img-cropped src='http://deepliquid.com/Jcrop/demos/demo_files/pool.jpg' selected='selected(cords)'></img-cropped>
    <div ng-show="cropped" id="cropped-image-container">
        <img id="preview" src='http://deepliquid.com/Jcrop/demos/demo_files/pool.jpg'>
    </div>
</div>
add the following custom styles to your style sheet
div#cropped-image {
    height150px;
    width150px;
    overflowhidden;
}

In the above HTML we are using a image to crop and a div which contains the cropped image. So, if we start cropping the original image, the new cropped image is showed in the div. (see this plnkr for live example: angularjs directive for image cropping )

Now add the following controller to your javascript file
app.controller('MainCtrl'function ($scope) {
    $scope.selected = function (cords) {
        $scope.cropped = true;
        var rx = 150 / cords.w;
        var ry = 150 / cords.h;
        $('#preview').css({
            width: Math.round(rx * boundx) + 'px',
            height: Math.round(ry * boundy) + 'px',
            marginLeft: '-' + Math.round(rx * cords.x) + 'px',
            marginTop: '-' + Math.round(ry * cords.y) + 'px'
        });
    };
});

When a user crops the image, the "selected" function inside the "MainCtrl" gets called which gets the cropped image's co-ordinates. Now using that co-ordinates we are applying css styles to the preview image(which is in the second div).

That's it. Here JCrop doesnot creates a new image , instead it just gives you the cropped image's co-ordinates. Using that co-ordinates you have to change the css of the image. See this stackoverflow question for more details about saving the cropped image to database. save cropped image - jcrop

Hope it helps you. Happy coding :-) :-)

For more articles on AngularJs visit: AngularJs


Read more...

AngularJs Directive for notifications

When ever we are building a webpage we may want to show some notification messages to the users. Here we are going to use JQuery's miniNotiication plugIn to show notifications. You can download this plugin from here: https://github.com/miniJs/miniNotification

download the zip file and add the miniNotification.js file to your project.

Add the following service to your services.js file.

app.factory('NotificationService', ['$rootScope', function ($rootScope) {

    var notificationService = {

        information: function (message) {
          $rootScope.$broadcast("notificationBroadcast", { "Message": message, "Type": 'information' });
        },

        success: function (message) {
          $rootScope.$broadcast("notificationBroadcast", { "Message": message, "Type": 'success' });
        },

        error: function (message) {
          $rootScope.$broadcast("notificationBroadcast", { "Message": message, "Type": 'error' });
        }
    };
    return notificationService;
}]);


we are going to call this service in our controllers whenever we want to show notifications. There are three types of notifications in the service.

1.Notification of type "information"
2.Notification of type "success"
3.Notification of type "error"

And now add the following directive to your directives.js file

app.directive('PostDataNotification', function () {

    return function (scope, element, attrs) {
        scope.$on('notificationBroadcast', function (event, args) {
            scope.notificationMessage = args.Message;
            $('.notification').miniNotification({ time: 3000 });
        });
    };

});


The html code to show the notification

  <div class="notification" post-data-notification="">
            <p>{{notificationMessage}}</p>
   </div>


we are using the "PostDataNotification" directive on the div. Inside the directive we are adding some text to  "notificationMessage".

Now we need to add some styles to notification div. (change the styles as per your requirement)

.notification {
    display: none;
    position: fixed;
    cursor: pointer;
    width: 100%;
    background: #EFEFEF;
    text-align: center;
    z-index: 9999;
    padding: 9px;
    padding-left: 0px;
}

    .notification p {
        font-size: 14pt;
        font-family: 'Segoe UI','Arial';
        margin-top: 5px;
        margin-bottom: 5px;
    }


We are almost done. The last thing is calling the service from our controller.

If you want to show a success notification when a record is saved to database. Then you just call the notificationsService from success function of the ajax/http call.

Example:

        $.ajax({
                type: "POST",
                url: serviceURL,
                data: "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: successFunc,
                error: errorFunc
            });

            function successFunc(data, status) {    
                     NotificationService.success('successfully added data');
            }

            function errorFunc() {
                      NotificationService.error('Error in adding data');
            }
        });


Here we are calling NotificationService which calls Notification directive (using $broadcast and $on).

Hope it helps you.

For more posts on JQuery visit: JQuery

For more posts on AngularJs visit: AngularJS

Read more...

multiple callback functions in javascript

In my previous post i have explained about what is a callback function. In this post i am going to explain about multiple callback functions in javascript and how to use multiple callback functions.

Using two callback functions


A callback function is a function which is passed as a argument to the other function, and the callback function is "called back" inside that other function. Javascript also provides us to use multiple callbacks functions. We can pass two callback functions as argument to other function and we can call those two callback functions from that functions.

In the following example i am going to show you how we can use two callback functions

Example :


      function successcallBack(successData){
          alert(successData);
      }

      function errorcallBack(errorData){
          alert(errorData);
      }

     function checkNumbers(a,b,callback1,callback2){
          if(a==b)
              callback1('equal');
          else
              callback2('not equal');
     }

      checkNumbers(5,5,successcallBack,errorcallBack);


In the above example we are passing two numbers to "checkNumbers" functions and checking they are equal or not. If both the numbers are equal then we are calling successcallBack function and if the numbers are not equal we are calling errorcallBack function.

In this way you can use multiple callback functions in javascript.

For more posts on javascript visit: javascript


Read more...

CallBack functions in Javascript

After a lot of investigation about callback on many sites, i got some knowledge on what are the callbacks and why we use callbacks. So i just want to share my knowledge here so that it will help some new javascript learners.

What is a callback function


According to wiki "a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time".  Generally a callback function is a function which is passed as a argument to the other function(say FuncA), and the callback function is "called back" inside that other function(FuncA) hance the name callback.

Syntax: 

The following is the syntax for a simple callback function

function multiplier(arg1,arg2,callback)
{
     callback(arg1*arg2);
}

multiplier(2,3,function(result){
   //do something with result
})


In the above example a anonymous function is passed as a callback function to "multiplier" function. Then from that "multiplier" function we have called the callback function.


passing a function as a callback to another function


Generally functions take input in the form of arguments and returns a value using return statement. But using javascript we can do things a little differently. Instead of waiting for a function to complete by returning a value , we can use callbacks to do it asynchronously.(read more about asynchronous programming here: Asynchronous programming). This is more helpful when we are making some Ajax request or Requesting some data from database(which takes some time to finish) etc. Instead of waiting for the call back to be called we can keep on doing other things.

let's see a simple example which uses callback function

function doTotal(marks1,marks2,marks3,callback){
    var total=marks1+marks2+marks3;
    callback(total);
}

doTotal(90,95,80,function(total){
   var avg= total/3;
   alert(avg);
})


In the above example we have passed a callback function as a argument to doTotal function. The doTotal functions calculates the "total" and calls the callback function by passing "total" to it. Now the callback function uses that "total" to calculate the "average".

Note: Actually we don't need callback in the above example. This can be done by using a regular return statement. Because calculating the sum don't take much time. We mostly use calbacks in the cases where the function takes some time to finish(like ajax requests).


Named callback functions


In the above example we have used anonymous function(function with no name). Now see the same example in which i have used named function as a callback.

function doAverage(total){
     var avg= total/3;
     alert(avg);
}

function doTotal(marks1,marks2,marks3,callback){
    var total=marks1+marks2+marks3;
    callback(total);
}

doTotal(90,95,80,doAverage);


Make Sure the Callback is a Function


Whenever we are using callback we have to ensure that the value passed as a passback is a function. We can check this by using the below code

function doTotal(marks1,marks2,marks3,callback){
    var total=marks1+marks2+marks3;
    if(typeof(callback) == 'function')
        callback(total);
     else
       //some other code
}

doTotal(90,95,80,function(total){
   var avg= total/3;
   alert(avg);
})


Here we are testing the callback value using a typeof operator to ensure that whatever is passed is actually a function.

I hope this will give you a basic idea on callbacks.

To read about how to use multiple callbacks visit: multiple callback functions


For more posts on javascript/jquery visit:  javascript/jQuery


Read more...