width based if else toggle in js

3097 views javascript
0

I might just be dumb but I can't seem to get some javascript code working

function toggleNav() {
            var sidebar = document.getElementById('side-bar');
            var back = document.getElementById('backspace');

            if (sidebar.style.width === "0") {
                sidebar.style.width = "400px";
                back.style.transform = "rotate(0deg)";
                back.style.right = "0";
            } else {
                sidebar.style.width = "0";
                back.style.transform = "rotate(180deg)";
                back.style.right = "-50px";
            }


        }

I'm trying to check the width of this element, then if it's 0px in width it expands using a CSS transition and the back id is the button that is toggling everything

answered question

maybe (sidebar.style.width == '0px')? just something to try. can you console.log(sidebar.style.width)?

what is back.style.transform = "rotate(0deg)"; doing?

no, I can't do console.log(sidebar.style.width)

back.style.transform = "rotate(0deg)"; is rotating an arrow

as you wrote it i think it does nothing

How about using sidebar.offsetWidth == 0, does that work for you?

thanks ewizard for the help

i got it to work

2 Answers

9

I got it to work after changing if (sidebar.style.width === "0") to if (sidebar.style.width === "0px") i see my error

posted this
9

if (sidebar.style.width === "0") should be if (sidebar.style.width == "0px")

posted this

Have an answer?

JD

Please login first before posting an answer.