Reputation: 23959
I am trying to measure the width of the current viewport to set variable thisWidth
but getting 'undefined'
var thisWidth;
var browserWidth = $(window).width();
if(browserWidth > 590){
var thisWidth= 180;
} else if(browserWidth > 350){
var thisWidth= 150;
}
alert(thisWidth); // undefined??
Is there a better way to do this?
The reason I am doing it is to change a width variable(thisWidth) based on viewport width whether it be mobile or whatever.
UPDATE - SOLVED Problem was, it was measuring before it had finished loading! Therefore coming in below 350 where finished width was 360 - weird actually
Upvotes: 0
Views: 111
Reputation:
As others have pointed out, the extra var
s are unnecessary and can be removed. If you look at the logic, there's one case where thisWidth
can be undefined after the if. What happens if browserWidth
is less than or equal to 350? Then neither of the assignments to thisWidth
will run. Add a final else to fix it.
var thisWidth;
var browserWidth = $(window).width();
if(browserWidth > 590){
thisWidth= 180;
} else if(browserWidth > 350){
thisWidth= 150;
} else {
thisWidth=42;
}
alert(thisWidth);
Upvotes: 0
Reputation: 406
Execute the code inside "jQuery ready" as:
$(function(){
// Your code here
})
Upvotes: 2
Reputation: 1783
The var
s are redundant since they make variables local to the function scope. They don't hurt, but make the code less clear.
I'm guessing you are missing a default value if browserWidth
happens to be > 350
Upvotes: 0