ipkiss ipkiss - 2 months ago 7
CSS Question

body not goes to left in responsive mode

I have the following example code:

JS Fiddle

For

viewport < 763px:



  • the menu is changed its style to vertical mode and hidden

  • the bar icon (id="bars") will show up, and when it is clicked, the menu is displayed by moving to the left 300px and so the body.



The problem is when the bar icon is clicked, without clicking the close icon (id="close-icon"), then resize the viewport larger than 763px, only the menu switching correctly as horizontal mode, while the body does not move to left as it should be.

Am I doing something wrong here?

Answer

Because you are setting the left properties with jquery, you can't override it cleanly with CSS. I would suggest doing something like:

JS Fiddle

// Run on page load or window resize
$(window).on('load resize', function() {
    var windowWidth = $(this).width();

    // If less than 763 (what you tried with media query)
    if (windowWidth > 763) {
      $('body').css('left', '0');
    }

    // If over/equal 763 and left menu open
    if (windowWidth <= 763 && $('#menu').css('left') == "0px") {
      $('body').css('left', '300px');
    }
});

Another option would be using CSS classes to handle it like:

JS Fiddle

CSS

.open, .close {
  transition: .2s;
}
body.open {
  left: 300px;
}
#menu.open {
  left: 0px;
}    
#menu.close {
  left: -300px;
}
@media screen and (min-width: 763px) {            
  .open, .close {
     transition: 0;
  }
  #menu.close, body.open, body.close {
    left: 0;
  }
}

Toggle classes with jquery:

$(function() {
  $("#bars").click(function() {
    $('#menu, body').removeClass('close').addClass('open');
  });

  $("#close-icon").click(function() {
    $('#menu, body').removeClass('open').addClass('close')
  });

});