Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behaviour of window.innerwidth

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

I am using the above code to find the available width of a web page. It works most of the time. But in some mobile browsers (Mobile Chrome and a few) and sometimes in desktop website 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, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36

This is one of the user agent where it is failed. Mostly it happen in mobile chrome in android browser.

like image 822
kannanrbk Avatar asked Mar 04 '17 09:03

kannanrbk


1 Answers

You might try forcing the test in the if to be a Boolean.

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

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

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

If this doesn't work then the issue is that you have found a bug in jQuery's width method.

like image 79
David Bradshaw Avatar answered Nov 09 '22 01:11

David Bradshaw