user6116037
user6116037

Reputation:

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();

}

Upvotes: 0

Views: 58

Answers (1)

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();

}

Upvotes: 1

Related Questions