Unexpected window behavior.

if(window.innerWidth) { return window.innerWidth; } return $(window).width(); 

I use the code above to find the available webpage width. He works most of the time. But in some mobile browsers (Mobile Chrome and several), and sometimes on the desktop on the desktop, it returns 0. I don’t know what went wrong?

Mozilla / 5.0 (Linux, Android 5.1.1, SM-J500M Build / LMY48B) AppleWebKit / 537.36 (KHTML, e.g. Gecko) Chrome / 56.0.2924.87 Mobile Safari / 537.36

This is one of the user agents where it does not work. This mainly happens on mobile Chrome in the Android browser.

+7
javascript jquery android google-chrome
source share
1 answer

You can try to make the test in if be logical.

 if(!!window.innerWidth) { return window.innerWidth; } return $(window).width(); 

Having more than return in a function is not always considered best practice. You can make this clear as follows.

 return !!window.innerWidth ? window.innerWidth : $(window).width(); 

If this does not work, the problem is that you found an error in the jQuery width method.

+5
source share

All Articles