Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create and call a custom function in jQuery

I need to create a simple function in jQuery which will call within other few functions

$(document).ready(function() {
  function reload_cart() {
    alert('reload cart called');
  }
});
$(document).ready(function() {
  reload_cart(); //i need to call from here.
});
$(document).ready(function() {
  $('a.add_to_cart').live('click', function (e) {
    reload_cart(); //i need to call from here.
  });
});

The error I get in firebug: reload_cart() is not defined.

like image 995
user1911703 Avatar asked Aug 23 '13 01:08

user1911703


People also ask

How do you define and call a function in jQuery?

Answer: Use the syntax $. fn. myFunction=function(){}

Can we call a function in jQuery?

Calling a JavaScript library function is quite easy. You need to use the script tag. As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.

What is $( function () in jQuery?

jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is: $(document). ready(function() { });

How do you call a variable function in jQuery?

var FunctionToCall; (function () { //...... FunctionToCall = function() { //...... }; //........ } (); And then you can call FunctionToCall.


2 Answers

reload_cart is local to your first $(document).ready() callback. You can't call it from an outside scope.

You should merge your functions together:

$(document).ready(function() {
    function reload_cart() {
        alert('reload cart called');
    }

    reload_cart();

    $('a.add_to_cart').live('click', function(e) {
        reload_cart();
    });
});

An even better solution would be to create a cart object, add reload to its prototype, and initialize it outside of all of the callbacks.

like image 136
Blender Avatar answered Oct 25 '22 02:10

Blender


Yes, because you declared the function within the scope of the first $(document).ready(function(){}) so it will not be available outside of that functions scope.

I am not sure why you would call $(document).ready() more than once. Try this:

$(document).ready(function(){
   function reload_cart() {
       alert('reload cart called');
   }

   reload_cart(); //i need to call from here.


   $('a.add_to_cart').live('click', function(e) {
       reload_cart(); //i need to call from here.
   });
});

Alternatively you can also declare your function outside of $(document).ready() and it will be globally available.

like image 26
ced-b Avatar answered Oct 25 '22 03:10

ced-b