Search code examples
cssresizewindowmedia-queries

Media query dynamic active/disable script on load and resize window


I'm working with a JS masonry grid. I want disable the script in the mobile version (width less than 800px).

I am trying with the next code:

window.addEventListener('resize', function(){
    if(window.innerWidth > 800){
        ...execute script
    }
});

All JS CODE

window.addEventListener('resize', function(){
  if(window.innerWidth > 900){    

    /* @license minigrid v1.6.0 - minimal cascading grid layout http://alves.im/minigrid */
    !function(t){"use strict";function e(t,e,n,o,r){var i=Array.prototype.forEach,f=t instanceof Node?t:document.querySelector(t);if(!f)return!1;var s=f.querySelectorAll(e);if(0===s.length)return!1;n="number"==typeof n&&isFinite(n)&&Math.floor(n)===n?n:6,f.style.width="";var u=f.getBoundingClientRect().width,l=s[0].getBoundingClientRect().width+n,a=Math.max(Math.floor((u-n)/l),1),c=0;u=l*a+n+"px",f.style.width=u,f.style.position="relative";for(var d=[],p=[],h=0;a>h;h++)p.push(h*l+n),d.push(n);i.call(s,function(t){var e=d.slice(0).sort(function(t,e){return t-e}).shift();e=d.indexOf(e);var r=p[e],f=d[e],s=["webkitTransform","MozTransform","msTransform","OTransform","transform"];return t.style.position="absolute",o||i.call(s,function(e){t.style[e]="translate("+r+"px,"+f+"px)"}),d[e]+=t.getBoundingClientRect().height+n,c+=1,o?o(t,r,f,c):void 0});var m=d.slice(0).sort(function(t,e){return t-e}).pop();f.style.height=m+"px","function"==typeof r&&r(s)}"function"==typeof define&&define.amd?define(function(){return e}):"undefined"!=typeof module&&module.exports?module.exports=e:t.minigrid=e}(this);

    (function(){
        minigrid('.grid', '.grid-item');

        window.addEventListener('resize', function(){
          minigrid('.grid', '.grid-item');
        });
      })();        
  }
});

I have two problems with this:
1) Doesn't work when I load the page, only works when I resize the window.
2) Doesn't work when I change from >800 to <800. Only works with the width in the moment of loading.

CODEPEN

Thank you.


Solution

  • Your script is only called with window resize event, to execute it when the page load you should use

    window.onload = function() {
        //your code 
    }
    

    Update:

    var oldWidth;
    
    window.addEventListener('resize', function(e){
        if(window.innerWidth > 800 || oldWidth > 800){
            try {
                minigrid('.grid', '.grid-item');
            } catch(e) {
                loadLib();
                minigrid('.grid', '.grid-item');
            }
    
            oldWidth = window.innerWidth;
        }
    });
    
    window.onload = function() {
        minigrid('.grid', '.grid-item');
        oldWidth = window.innerWidth;
    }
    
    function loadLib() {
        // minigrid code
    }
    

    codepen