0

I have found an example on http://www.w3schools.com/ of how to create a responsive navigation bar

The example has a little bit of JavaScript in the form of a if/else statement. I would prefer to use a switch statement.

However, my switch statement does not work when i click the icon and does not provide any errors.

Example's JS code:

    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
        x.className += " responsive";
    } else {
        x.className = "topnav";
    }

My Switch statement:

var x = document.getElementById("myTopnav");
switch (x) {
    case "topnav":
        x.className += " responsive";
        break;

    default:
        x.className = "topnav";
}
1
  • make it switch (x.classname) rather than switch (x) --- and I was a day late and a dollar short. lol Commented Jan 24, 2017 at 19:48

2 Answers 2

3

You're comparing x:

switch (x)

But the original code is comparing x.className:

if (x.className === "topnav")

Switch on x.clasName instead:

switch (x.className)
Sign up to request clarification or add additional context in comments.

Comments

2

You are very close!

Just swap in x.className in your switch(x) statement, and you're good to go:

var x = document.getElementById("myTopnav");
// use x.className below...
switch (x.className) {
    case "topnav":
        x.className += " responsive";
        break;

    default:
        x.className = "topnav";
}

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.