how to create and call a custom function in jQuery
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.
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.
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');
}
});