Dimitris Damilos
Dimitris Damilos

Reputation: 2438

Pass variable between functions

I have the following line of code that is executed inside the $(document).ready:

$('#sliding_menu_area').toggle(effect, reAlign);

reAlign is a function that is declared outside of the $(document).ready main function in my .js file.

I have a variable called tag that is declared also inside the $(document).ready and I need to pass the variable to the reAlign function. I tried

$('#sliding_menu_area').toggle(effect, reAlign(tag));

but it didn't work. Can I declare the tag variable as a global so functions declared outside of $(document).ready to be able to access it? So far the functions declared inside the $(document).ready can access it just fine.

Any ideas?

Upvotes: 0

Views: 124

Answers (4)

Ruan Mendes
Ruan Mendes

Reputation: 92274

Karoly's answer works, another alternative is to do the following: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind

$('#sliding_menu_area').toggle(effect, reAlign.bind(window, tag));

That binds your function so that when it's called, it's called with window as the this variable and tag as the first argument to the function. Basically the same thing that Karoly suggested, with a different idiom.

Upvotes: 1

Dan D.
Dan D.

Reputation: 74645

If the reAlign function needs to know the DOM element (which is passed as this), it would be better to use:

$('#sliding_menu_area').toggle(effect, function () {
  reAlign.call(this, tag);
});

Upvotes: 0

Kevin Nelson
Kevin Nelson

Reputation: 7663

I would generally avoid making anything global...or at least conserve your global namespace as much as possible. For instance, I have a Page class, which I use for various functions, such as Page.notify("some message"). When I need to make something accessible to the entire page, I create a variable like Page.Tag. If you only need tag for the reAlign method, then go with Karoly's suggestion and avoid making something global that doesn't truly need to be global.

Upvotes: 2

Karoly Horvath
Karoly Horvath

Reputation: 96258

$('#sliding_menu_area').toggle(effect, reAlign(tag));

your code executes reAlign with the tag argument, and then passes the return value to toggle (as the second argument).

$('#sliding_menu_area').toggle(effect, function() { reAlign(tag); });

Upvotes: 3

Related Questions