JQuery - intercepting a variable from another function

I have two functions on my page. I am trying to find a way to access a variable in function 1 inside function 2:

$(function() { $('a[id=1]').live("click", function(event) { event.preventDefault(); var Var1 = "something1"; }); }); $(function() { $('a[id=2]').live("click", function(event) { event.preventDefault(); var Var2 = event.var1; }); }); 

So, I'm sure mine above is wrong, but you can see how in function 2 I am trying to capture a variable from the first function.

Is there a way I can do this? I don’t know why, but I keep thinking that this has something to event.var1 with event.var1 or the functionality of the event.

+7
source share
2 answers

You need to declare a variable outside of both functions, in the area that they can access. I suggest combining your two document handlers into one function and declaring a variable here:

 $(function() { var var1; // may want to assign a default $('a[id=1]').live("click", function(event) { event.preventDefault(); var1 = "something1"; }); $('a[id=2]').live("click", function(event) { event.preventDefault(); var var2 = var1; }); }); 

Or you can make the variable global if you need to access it from other places.

Please note that the events of two clicks have nothing in common with each other, so they, of course, do not use the event data. In addition, clicking on the second anchor can occur before clicking on the first, so you can specify var1 as the default and / or test for undefined to use it in the second click handler.

(I also changed var1 to var1 because the JS convention should start the variable names with a lowercase letter - you don't have to follow the convention, but I would recommend it.)

+13
source

Each event will be unique for each click, you can save the result in a global variable in the window object and take care of the order of events

 $(function() { $('a[id=1]').live("click", function(event) { event.preventDefault(); window.Var1 = "something1"; }); 

});

 $(function() { $('a[id=2]').live("click", function(event) { event.preventDefault(); var Var2 = window.Var1; }); 

});

+2
source

All Articles