简体   繁体   中英

How to fire my jQuery on resize and detect the width

I have this script that I wrote but I need help. It's suppose to work like a off-canvas menu for mobile/tablets

The issue is that if i resize the browser and open up the menu again the marginLeft of -270px isn't ideal since if i resize the browser the -270px of the original mark don't match up since its a different viewport size.

Right now I am pushing the body to the left using marginLeft:-270px this works fine on load BUT if i resize the browser everything gets all buggy.

Any help would be appreciated.

jQuery('.menu-toggle').toggle(function() {
        jQuery(this).addClass('open');
        jQuery('#top-main-nav-container').addClass('active');

        jQuery('body').animate({
          marginLeft: '-270'
        }, 700);
        jQuery('.main-navigation ul').css('display','block');

      },function() {
         jQuery(this).removeClass('open');
         jQuery('#top-main-nav-container').removeClass('active');

         jQuery('body').animate({
           marginLeft: '0'
         }, 700);

         jQuery('.main-navigation ul').css('display','none');

      });`

CSS

.menu-toggle.open {
    padding: 30px 25px 500% 100%; 
    background-color: rgba(165, 166, 168, 0.952941);
}
body.active {
    margin:0;
    -moz-transition: margin .5s;
    -webkit-transition: margin .5s;
    transition: margin .5s;
}
#top-main-nav-container.active {
    right:0;
    -moz-transition: all .5s;
    -webkit-transition: all .5s;
    transition: all .5s;
}
$(window).on("resize", function () {

    // Invoke the resize event immediately
    }).resize();

The last .resize() call will run this code upon load.

OR

The cleanest way is to just bind it also to the load event:

$(window).on('load resize', function () {

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM