StuyvesantBlue
StuyvesantBlue

Reputation: 145

Converting javascript function to global variable

I've been struggling to convert a JavaScript function to a global variable.

I've got 2 files in total that are basically part of the entire function, here is the JavaScript function.

<script type="text/javascript">
$.get("banner1.php", function(getbannerlink1) {
$("#banner1").load(getbannerlink1+ " #productImage");
// var window.bannerlink1=getbannerlink1; (this doesn't want to work)
});
<script>

Basically banner1.php selects ONE random URL out of an array, and echoes the URL. This JavaScript then gets the URL, and then does a .load() function of that URL and gets the #productImage class from that URL, basically it gets the product image from the random URL. That works all good. Now I need to convert the getbannerlink1 variable to a global variable, because I would like to use the link outside of this function as well.

I've tried using the following just before closing the function:

var window.bannerlink1=getbannerlink1;

but this is just destroying the function altogether :/

What am I doing wrong?

Upvotes: 0

Views: 184

Answers (2)

epascarello
epascarello

Reputation: 207511

Drop the var

window.bannerlink1 = getbannerlink1; 

Ideally you would avoid using a lot of globals and use a global namespace to hold the values.

Upvotes: 2

apsillers
apsillers

Reputation: 115950

var window.bannerlink1 is a syntax error. var should only be used with variable identifiers, which may not contain a period.

You want to set a property of window, not declare a new variable name, so just drop the var.

Upvotes: 2

Related Questions