简体   繁体   中英

Run JS when screen width is this

I have this js that I want to only run when the screen size is 800 or below, as it enables swiping. Please help I cant figure out away.

var snapper = new Snap({
  element: document.getElementById('content')
});

and the Snap is linked by

Thanks for any help.

EDIT:

<script> 

            $(function() {
                var SmartMenu           = $('#SmartMenu');
                    MainMenu            = $('.MainMenu');

                    PortfolioMenu       = $('#Portfolio');
                    PortfolioSubMenu    = $('.subMenu');

                    SmartMenuOpen       = $('#SmartMenuOpen');
                    wrapperHeader   = $('.wrapperHeader-Top');

if(window.innerWidth <= 800) {
                        var snapper = new Snap({
  element: document.getElementById('W')
});
}


                $(SmartMenu).on('click', function(a) {
                    if( snapper.state().state=="left" ){
                    snapper.close();
                } else {
                    snapper.open('left');
                }
                });
</script>
if(window.innerWidth <= 800) {
   // Your code here
}

That should do the trick the first time.

EDIT 1 : If you want it to change whenever the browser is resized

window.onresize = function(event) {
  if(window.innerWidth <= 800) {
    // Your code here
  }
}

But do make sure that the code you include will work correctly if called multiple times when the browser is resized.

EDIT 2 With access to jQuery: #2 to support Snap API and to support init

var snapper;

function initSnapper() {
  if($(window).innerWidth() <= 800) {
    if(snapper === undefined) {
      snapper = new Snap({
        element: document.getElementById('W')
      });
    } 
    else {
      snapper.enable();
    }
  }
  else if(snapper !== undefined) {
    snapper.disable();
  }
}


$(window).resize(initSnapper);
initSnapper();

This will initialize snapper when the page loads and will call initSnapper when the page is resized. And you will want to check if snapper exists before checking the state like

if( snapper && snapper.state().state=="left" ){
  // snapper code
}

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