简体   繁体   中英

How do I make the if/else statement get checked every time my function is called (JavaScript)?

so what I am trying to do is make the if/else statement in the function below get checked every time the function is called. I call it using

onclick="openNav()"

in my HTML. Thank you so much for your help, sorry if this is a lame question as I am new to JavaScript.

Code below:

 var intViewportWidth = window.innerWidth; function openNav() { $("body").css("background-color", "rgba(0,0,0,.4)"); if (intViewportWidth < 1200) { $("header nav").css("width", "100%"); $("body").css("margin-right", "100%"); } else { $("header nav").css("width", "30%"); elBody.css("margin-right", "30%"); } $("#hamburger").hide(); } 

Use below snippet. Unless getting width is inside function, intViewportWidth will not change.

 function openNav() { $("body").css("background-color", "rgba(0,0,0,.4)"); var intViewportWidth = window.innerWidth; if (intViewportWidth < 1200) { $("header nav").css("width", "100%"); $("body").css("margin-right", "100%"); } else { $("header nav").css("width", "30%"); elBody.css("margin-right", "30%"); } $("#hamburger").hide(); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM