0

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.

1 Answers1

2

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.

Carele
  • 756
  • 3
  • 13
  • Thank you for the explanation. Unfortunately, it is not what I am looking for. I have tried changing the scope of the variables to no avail. I believe it is the nature of my variable which is causing it no not work. – Marcus Wallace Jun 22 '16 at 16:49
  • Then maybe you should make a 3rd function doing the selection with "this" as an argument ? It would return an array with your 4 objects You would then call that function with the proper index for each thing. Could that be a solution ? – Carele Jun 22 '16 at 21:11