Keep in mind $(window).width()
and the width calculated by the CSS is not same because of the scrollbar, in some cases .innerWidth
will work but yeah that is also something not to be dependent upon.
If IE9 support is not required then you can just use window.matchMedia()
(MDN documentation).
if (window.matchMedia('(max-width: 768px)').matches) {
$("ul.nav li.dropdown ul.dropdown-menu").show();
} else {
$("ul.nav li.dropdown ul.dropdown-menu").hide();
}
window.matchMedia
is fully consistent with the CSS media queries and the browser support is quite good: http://caniuse.com/#feat=matchmedia
Using Modernizr:
Modernizr is a JS based library, if you have to support more browsers you can use Modernizr's mq method, it supports all browsers that understand media queries in CSS.
if (Modernizr.mq('(max-width: 768px)')) {
$("ul.nav li.dropdown ul.dropdown-menu").show();
} else {
$("ul.nav li.dropdown ul.dropdown-menu").hide();
}
Source