When changing the width of the browser, the body should leave (left: -181px) and stand in place (left: 0). Everything, in principle, works. Here is the working piece of code:

$(window).resize(function(){ if ($(document).width() >= 751){ $('body').animate({ left: '0' }); } if($('.menn').css('right') == '0px' && $(document).width() < 751){ $('body').animate({ left: '-181' }); } }); 

But it takes a very long time to react. For example, when narrowing the screen, the program “thinks” for a very long time and only then the animation is applied to the body left: '-181'.

    2 answers 2

    Perhaps the case is no timeout. When the window is resized, the resize event can occur many times and repeatedly call your function with animation.

    Usually when resize set timeout (in the example 300 ms) to perform actions. If another resize event is received during this time, the timeout is reset by another 300 ms. And only after the user has finished resizing the window and nothing happens for 300 ms, call their resize response functions:

     var resizeTimer; $(window).resize(function(){ clearTimeout( resizeTimer ); resizeTimer = setTimeout( function() { if ($(document).width() >= 751){ $('body').animate({ left: '0' }); } if($('.menn').css('right') == '0px' && $(document).width() < 751){ $('body').animate({ left: '-181px' }); } }, 300 ); }); 

    You can do it not on jquery animations, but on css animations with the participation of media queries:

     body { width: 100%; overflow: hidden; left: 0; transition: left 300ms; position: relative; } @media (max-width: 750px) { body { left: -181px; transition: left 300ms; } } 
     Test1 test2 test3 test4 test5 test6 

    • one
      Other things being equal, css animation is always faster than js. - KAGG Design