10

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 am sure my above is incorrect but you can see how in function 2 I am trying to grab a variable from the first function.

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

2
  • 1
    The second click's event has nothing to do with the first click's event. Commented Mar 12, 2012 at 23:59
  • So to confirm, you are setting a variable with one click, and using it with the second click? Commented Mar 13, 2012 at 0:01

2 Answers 2

23

You need to declare the variable outside both functions, in a scope they can both access. I suggest combining your two document ready handlers into a single function and declaring the variable there:

$(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 could make the variable a global if you need to access it from other places too.

Note that the two click events have nothing to do with each other so they certainly don't share event data. Also, a click on the second anchor may occur before a click on the first, so you may want to give var1 a default value and/or test for undefined befor using it inside the second click handler.

(Also I've changed Var1 to var1 because the JS convention is to start variable names with a lowercase letter - you don't have to follow the convention, but I'd recommend it.)

Sign up to request clarification or add additional context in comments.

Comments

5

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.