0

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

3
  • Works fine. Try remove var's inside if statement Commented Mar 2, 2014 at 10:26
  • 1
    You'll probably need a thisWidth too if the viewport is <350! Commented Mar 2, 2014 at 10:26
  • 2
    Post your solution in an answer, not the question. Commented Mar 2, 2014 at 10:31

3 Answers 3

2

Execute the code inside "jQuery ready" as:

$(function(){ // Your code here })

Sign up to request clarification or add additional context in comments.

Comments

0

The vars 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

Comments

0

As others have pointed out, the extra vars 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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.