20

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.

0

3 Answers 3

35

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your fast response. may i have a sample code of how do i create cart object and call it from anywhere. i don't have any experience of prototype much.
MDN has very nice articles on these subjects: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…
8

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.

Comments

7

Put your function definition:

function reload_cart() {
    alert('reload cart called');
}

Outside document.ready.

Currently, Its scoped inside the document.ready handler only.

$(document).ready(function(){
//reload_cart is only available here
    function reload_cart() {
        alert('reload cart called');
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.