IF condition in javascript only works once

Asked

Viewed 124 times

1

I’m trying to make a Side Navigation, so in 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 modifications:

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, IE, it opens and closes then no longer works.

  • Where is there Java there?

  • You can make an example in Jsfiddle?

  • 1

    Never make the side-Nav appear and disappear by changing the width, use Transform’s translateX css. When you change the width you generate several expensive Paints that are made by the CPU, if you use translateX you will have extremely light Paints run by GPU.

1 answer

5


The value that .style.width returns is a string. You have 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";
    }
}
  • Friend, it worked perfectly, however, to work the first time, I have to click twice. knows why?

  • @Thomaserichpimentel probably because that element #mySidenav does not have a style defined from start. Only in CSS will not be read by .style.width. Put forehead style="width: ..." in HTML. If you got it wrong do a jsFiddle to be clearer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.