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
.
Answer: Use the syntax $. fn. myFunction=function(){}
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.
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() { });
var FunctionToCall; (function () { //...... FunctionToCall = function() { //...... }; //........ } (); And then you can call FunctionToCall.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With