IF condition in javascript only works once

1

I'm trying to make a Side Navigation , so on internet search, I found a little tutorial on the site: How TO - Side Navigation

However, in my example I wanted a single button to open, and close, so I made the following changes:

function closeNav()
{    
    if (document.getElementById("mySidenav").style.width < 250)
    {
        document.getElementById("mySidenav").style.width = "250px";
    }
    else
    {
        document.getElementById("mySidenav").style.width = "40px";
    }  
}

But, it only works once, that is, it opens and closes after it no longer works.

    
asked by anonymous 01.12.2016 / 12:47

1 answer

5

The value that .style.width returns is a string . You need to use a type converter to have a number and use the < operator.

You could do it like this:

function closeNav() {
    var sideNav = document.getElementById("mySidenav");
    if (parseInt(sideNav.style.width) < 250) {
        sideNav.style.width = "250px";
    } else {
        sideNav.style.width = "40px";
    }
}
    
01.12.2016 / 13:00