jquerynavbarsuperfish

jQuery addCss and .removeCss only works on page refresh


To the unordered list

<ul class="sf-navbar sf-menu" id="sfmenu">

I am using following jQuery code but it works only on page refresh.

jQuery(document).ready(function() {
    if ($(window).width() > 768) {
        $('#sfmenu').removeClass( "nav navbar-nav" ).addClass('sf-navbar sf-menu');
    }
    if ($(window).width() < 768) {
        $('#sfmenu' ).addClass( "nav navbar-nav" ).removeClass( "sf-navbar sf-menu" );
    }
});

I also tried with this:

jQuery(document).ready(function() {
    if ($(window).width() > 768) {
        $('#sfmenu').removeClass( "nav navbar-nav" );
        $('#sfmenu').addClass('sf-navbar sf-menu');
    }
    if ($(window).width() < 768) {
        $('#sfmenu' ).addClass( "nav navbar-nav" );
        $('#sfmenu' ).removeClass( "sf-navbar sf-menu" );
    }
});

But no success.

Also I tried with UL as

   <ul class="" id="sfmenu">  

But still no success. Suggestions will be highly appreciated!


Solution

  • Use $(window).resize() like,

    jQuery(document).ready(function() {
       function sfmenuToggle() {
          if ($(window).width() > 768) {
              $('#sfmenu').removeClass( "nav navbar-nav" )
                          .addClass('sf-navbar sf-menu');
          }
          if ($(window).width() < 768) {
              $('#sfmenu' ).addClass( "nav navbar-nav" )
                           .removeClass( "sf-navbar sf-menu" );
          }
        }
        // on window resize
        $(window).resize(function(){
            sfmenuToggle();
        });
        // on page load
        sfmenuToggle();
    });