I've read several questions about using a variable in multiple functions by making it global (defining it outside of a funciton)... however, I have a function that produces a dynamic value on click (gets an href value of a link) -
I need to pass that resulting variable into another function.
Basically, I'm grabbing a clicked link's href value and then wanting to pass it to Ajax if a confirmation box is selected.
It doesn't seem that declaring the variable globally would work, as it's definition comes only if an onclick event is triggered.
Any thoughts?
You can create the variable as a global with a value of null, and then set it in your first function. After you read the variable in your second function, set the value back to null.
Example:
var someGlobal = null;
function f1( ) {
someGlobal = 'someValue';
}
function f2( ) {
if( someGlobal == null ) {
// the global isn't set! might want a message of some sort, or just ignore it
return;
}
var myLocal = someGlobal;
someGlobal = null;
// do something with myLocal here
}
Best way to achieve this is define the variable as you've read through outside sources outside of anything that is function(){}. What I usually do for my global variables for example is either set a default value or set it to a blank value above any of the other code I write in that JS.
Example:
var myHREFval;
$('a').click(function(){myHREFval = $(this).attr('href');});
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