Search code examples
jquerytwitter-bootstrapjasny-bootstrap

Bouncing between Bootstrap Navbar and Jasny Off Canvas based on viewport width


I am a bit new to jQuery and am working with Bootstrap and Jasny Off Canvas. I am wanting to flick between Bootstraps navbar on all devices over 900px and Jasny's off canvas menu for all devices under 900px.

To achieve this I am using the following:

 <script>   
        $(window).bind("load resize", function() {
            var width = $(window).width();
            if (width <= 900) {
                $('.nav-selector').removeClass('navbar navbar-default');
                $('.menu-items').removeClass('collapse navbar-collapse');
                $('.nav-items-selector').removeClass('nav navbar-nav');
                $('.nav-selector').addClass('navmenu navmenu-default navmenu-fixed-left');
                $('.nav-items-selector').addClass('nav navmenu-nav');
            }
            else {
                $('.nav-selector').removeClass('navmenu navmenu-default navmenu-fixed-left');
                $('.nav-items-selector').removeClass('nav navmenu-nav');
                $('.nav-selector').addClass('navbar navbar-default');
                $('.menu-items').addClass('collapse navbar-collapse');
                $('.nav-items-selector').addClass('nav navbar-nav');
            }
        });         
    </script>

This works but for my own learning, is there a more eloquent way of changing between to nav types without having either 2 completely different navs (hidden and visible on different media queries) or having to customise every line of CSS for both nav types.

I hope this makes sense, please ask if it doesn't.


Solution

  • You can define the whole nav as a string and depending on the size, you insert it as the html.

    var width = $(window).width();
    var nav1 = '<div>a very long string</div>';
    var nav2 = '<div>an equally long string</div>';
    if (width <= 900) {
      $('#navContainer').html( $(nav1) );
    } else {
      $('#navContainer').html( $(nav1) );
    }
    

    You can optimize this by adding a unique id to each nav and checking if they're already there so that you don't modify the DOM for nothing.