Reputation: 1
I'm still fairly new to JavaScript and Jquery, but if anyone can help I'd really appreciate it as I've been struggling with this one for hours.
I have a function that's part of a larger plugin function (QueryLoader2 by Gaya if anyone's familiar). In the function I'm looking at, there's a part where it gets a percentage value of items that are being loaded in the page:
var completeImageLoading = function () {
qLdone++;
var percentage = (qLdone / qLimageCounter) * 100;
if (qLoptions.percentage == true) {
$(qLpercentage).text(Math.ceil(percentage) + "%");
}
if (qLdone == qLimageCounter) {
destroyQueryLoader();
}
}
The part "var percentage" is the part that I need to be gloabal, so the numeric percentage value can be used by another function completely outside of this one (in another Javascript file actually). I've tried removing the 'var' but that doesn't work.
If anyone can help, I'd really appreciate it! Thanks
Upvotes: 0
Views: 95
Reputation: 1990
If you send more information about your script will be more easier to help you, but I'll try anyway.
First, you are doing something wrong for a Global variable return undefined.
Look at this http://jsfiddle.net/WyShw/3/, the variable is defined (doesn't matter where), and is returning the value. Just verified if you are calling the function (completeImageLoading()) before call the variable, because in this case, you don't need to define the variable, it was defined when you call the function completeImageLoading(). We defined with a default value in case of we never call it in a function.
Upvotes: 0
Reputation: 2789
Try this
var percentage;
var completeImageLoading = function () {
qLdone++;
percentage = (qLdone / qLimageCounter) * 100;
if (qLoptions.percentage == true) {
$(qLpercentage).text(Math.ceil(percentage) + "%");
}
if (qLdone == qLimageCounter) {
destroyQueryLoader();
}
}
Upvotes: 0
Reputation: 303559
Outside your function put:
var percentage;
Inside your function put (no var
):
percentage = (qLdone / qLimageCounter) * 100;
Basically, in JavaScript local variables declared in the same spot as a function may be used (both read and written) inside that function. A function using such local variables is called a closure.
Upvotes: 1