Search code examples
jqueryviewportwindow-resize

Troggle class on viewport


I have my navigation. When I reach viewport < 860px the class <nav class="nav" needs to be <nav class="nav-mobile" I came pritty far but really need to get rid of the ``class="nav". Below script only ADDS the nav-mobile but doesn't remove class="nav".

    $(window).on('resize', function () {
        $('.nav').toggleClass('nav-mobile', $(window).width() < 860);
    });

Solution

  • jQuery solution

    function appResize()
    {
       if($(window).width() < 860){
            $('nav').addClass("nav-mobile");
            $('nav').removeClass("nav");
          }
          else{
            $('nav').removeClass("nav-mobile");
            $('nav').addClass("nav");
          }
    }
    
    $(function(){
    appResize();
    })
    
    $(window).on('resize', function () {
      appResize();
    });
    

    working demo http://jsfiddle.net/7fs7xrma/1/

    CSS3 solution use CSS media queries

    html

    <nav class="nav"></nav>
    

    css

    .nav{
         background:red; 
         height:20px;
        }
    
    @media screen and (max-width : 860px){
    .nav{
        background:blue;
        }
    }
    

    demo on jsFiddle http://jsfiddle.net/7fs7xrma/2/