1

I have 2 navigation buttons, 'a' and 'b', where 'a' links to page 'A' and 'b' links to page 'B'. When the page loads, page 'A' is visible by default and page 'B' is hidden by default. When link 'b' is clicked, page 'A' is faded out to opacity 0 and reduced in height via the jQuery 'toggle' method, while page 'B' is faded in to opacity 1 and increased in height to full size via the jQuery 'toggle' method. When link 'a' is clicked again, the opposite happens where page 'b' is once again hidden from view and page 'a' brought back to view using the same methods.

What I'm having trouble with is when the link to the current page being displayed is clicked again, the current page just goes blank; if page 'A' is already loaded, and I click on link 'a', the whole page goes blank, which I don't want. What I have tried is the following:

var i = "a";

function a() {
  if (i != "a") {
    var i = "a";    
    jQuery(animation to hide page 'A');
    jQuery(animation to make visible page 'B');
  }
}

function b() {
  if (i != "b") {
    var i = "b";
    jQuery(animation to hide page 'B');
    jQuery(animation to make visible page 'B');
  }
}

I have figured out that the value for variable 'i' that I set inside a function is only effective inside the function and that outside the function, the variable's value remains as 'a' and hence link 'a' is never clickable while link 'b' is always clickable and also results in a blank page.

How can I write the correct javascript to do what I want it to do?

2 Answers 2

5

Drop the var keyword inside both functions and it will modify the global i variable.

Your code is actually very misleading because you're assigning i to a function, you might want to just change it to use strings, like so:

var i = "a";

function a() {
  if (i != "a") {
    i = "a";    
    jQuery(animation to hide page 'A');
    jQuery(animation to make visible page 'B');
  }
}

function b() {
  if (i != "b") {
    i = "b";
    jQuery(animation to hide page 'B');
    jQuery(animation to make visible page 'B');
  }
}
Sign up to request clarification or add additional context in comments.

Comments

5

You are defining a new variable i again in the function because you are using var before i. Change them to as follows:

var i = a;

function a() {
  if (i != a) {
    i = a;    
    jQuery(animation to hide page 'A');
    jQuery(animation to make visible page 'B');
  }
}

function b() {
  if (i != b) {
    i = b;
    jQuery(animation to hide page 'B');
    jQuery(animation to make visible page 'B');
  }
}

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.