Roy Berris
Roy Berris

Reputation: 1592

JS, CSS Menubar Toggle

Hello I want to make a Menu thats pops out of the side when I click a button. I have it all set up with the CSS but the Javascript part doesn't work. I want to test if the width of menubarWrapper is equal to 300 then the width of the menubarWrapper needs to change to 0px and if it isn't equal to 300px than change it to 300px. I have the following JS:

function menuBarToggle() {
var menuWrapper = document.getElementById('menuWrapper');
if menuWrapper.width == 300 {
    menuWrapper.style.width = "0";
} else {
    menuWrapper.style.width = "300";
    }
}

I also tried in the IF statement menuWrapper.style.width but that doesn't work also

Upvotes: 0

Views: 154

Answers (3)

Michael Hays
Michael Hays

Reputation: 6908

There are other answers that are just fine --

  • use "300px", not "300"
  • Surround your conditional with a parentheses.

(You'll need both, by the way.)

But I wanted to make sure that somewhere on this page, someone pointed out that this is a very brittle way of toggling. You have a magical, hardcoded integer for the size, which might break if you ever wanted to style things differently. And if you decide one day to fade out the menu, then the test won't work at all.

Might I suggest that, instead, you create two classes in CSS:

.menu-item { width: 300px; }
.menu-item.collapsed { width: 0; }

And then in javascript, you'll only have to write the following:

function menuBarToggle() {
  var menuWrapper = document.getElementById('menuWrapper');
  menuWrapper.classList.toggle('collapsed');      
}

Not only is the intention easier to read, but this will allow you to swap out the behavior if you decide that, instead of purely narrowing the menu, you might want it to fade out, or animate it to the left, or... well... whatever can come up with.

Upvotes: 3

A.J. Uppal
A.J. Uppal

Reputation: 19284

When changing the width of an element via style.width, you have to append px to the end of the string:

function menuBarToggle() {

    var menuWrapper = document.getElementById('menuWrapper');
    if menuWrapper.width == 300 {
        menuWrapper.style.width = "0px";
    } else {
        menuWrapper.style.width = "300px";
        }
    }

Upvotes: 0

Zlatko Vujicic
Zlatko Vujicic

Reputation: 353

Your script has a typo. Add '()' for an if statement.

function menuBarToggle() {
    var menuWrapper = document.getElementById('menuWrapper');
    if (menuWrapper.width == 300) {
        menuWrapper.style.width = "0";
    } else {
        menuWrapper.style.width = "300";
    }
}

Upvotes: 0

Related Questions