2

I want to write jquery code that when my website load via mobile devices show all sub menu .This code exist into Bootstrap.css file. Please advice.

        @media screen and (max-width: 768px) {         
      ul.nav li.dropdown ul.dropdown-menu{ display: block; }
}
hmahdavi
  • 2,250
  • 3
  • 38
  • 90

3 Answers3

4

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

Community
  • 1
  • 1
void
  • 36,090
  • 8
  • 62
  • 107
1

Best solution in this article : http://www.sitepoint.com/javascript-media-queries/

var mq = window.matchMedia( "(min-width: 500px)" );
if (mq.matches) {
    // window width is at least 500px
}
else {
    // window width is less than 500px
}
Gregorie
  • 129
  • 6
1
if ($(window).width() <= 768){
    $('ul.nav li.dropdown ul.dropdown-menu').css('display', 'block');
}
Kevin Bui
  • 524
  • 3
  • 10