Marcus Wallace
Marcus Wallace

Reputation: 57

Sharing variables between more than 1 function

I am creating a simple accordion menu with two ways of navigating.

  1. By clicking on the step title
  2. By clicking on "Next / Prev" buttons inside the step.

JSFiddle

My js code looks like this:

$(document).ready(function(){

// Click on TITLE
$(".step-title").click(function(){
  
  var this_title = $(this).parents(".step").children(".step-title");
  var this_content = $(this).parents(".step").children(".step-content");
  var that_title = $(".step-title");
  var that_content = $(".step-content");
    
  if (this_title.hasClass("active"))
  {
    this_title.removeClass("active");
    this_content.slideUp(200);

  } else {
    that_title.removeClass("active");
    this_title.addClass("active");
    that_content.slideUp(200);
    this_content.slideDown(200);
    }
  });
  
// Click on BUTTON
$(".save").click(function(){
  
  var this_title = $(this).parents(".step").children(".step-title");
  var this_content = $(this).parents(".step").children(".step-content");
  var that_title = $(".step-title");
  var that_content = $(".step-content");
    
  if (this_title.hasClass("active"))
  {
    that_title.addClass("active");
    this_title.removeClass("active");
    that_content.slideDown(200);
    this_content.slideUp(200);
  }
});

});

As you can see I am reusing the same variables on both functions and hence the root of my question.

** QUESTION ** Is there a way for me to share those variables in multiple functions?

When I take them out of the local scope of the function they don't work.

Thank you for your help.

Upvotes: 0

Views: 46

Answers (1)

Carele
Carele

Reputation: 774

They are multiple ways to go about it.

Global variable are considered a bad thing (even errors in strict mode) to do in Js so maybe you should keep it as it is, or make a function with an argument (that would trigger only a part of your function).

If you really want to set a "global" variable, you have to ommit the var before the name of your variable :

foo = bar

However as I said, it is considered an error in strict mode, and can lead to different issues. A "cleaner" way to go about it, would be assigning the variable to the window object.

window.foo = bar

Would work like a global variable, with less downsides and more readability.

Upvotes: 2

Related Questions