Search code examples
javascriptjquerymedia-queriesgsap

Including two window.matchMedia into script


I am trying to add this:

var mql = window.matchMedia("(max-width: 480px)"), window.matchMedia("(max-height: 479px)");

into my existing script right now which only has:

var mql = window.matchMedia("(max-width: 480px)");

When I add the second .matchMedia mentioned above, the script doesn't fire at all.

I've tried adding two variables:

var mqls = [ 
  window.matchMedia("(max-width: 480px)"),
  window.matchMedia("(max-height: 479px)")
];

function mediaqueryresponse(mql){
  document.getElementById("match1").innerHTML = mqls[0].matches // width: 480px media match?
  document.getElementById("match2").innerHTML = mqls[1].matches // width: 479px media match?
}

Here is the script working before adding max-height: jsFiddle. Please note that the script is at the bottom of js panel. The top script is for TweenMax to animate the lines.

And here is the script with the added variables: jsFiddle.


Solution

  • If you want the smallBlock() animation to run when min-width is 479px or min-height is 480px then I think adding a comma , in between the queries should do the trick.

    Take a look at this jsFiddle and test it out if it produces the result you are looking for.

    JavaScript:

    var mql = window.matchMedia('(min-width: 479px), (max-height: 480px)');
    function smallBlock() {
        setTimeout(function () {
            TweenLite.defaultEase = Linear.easeNone;
            TweenLite.set('.square', { visibility: 'visible' });
            var tl = new TimelineLite();
            tl.fromTo('.l1', 2, { height: 0 }, { height: 27 });
            tl.fromTo('.l2', 3, { width: 0, }, { width: 45 });
            tl.fromTo('.l3', 2, { height: 0 }, { height: 27 });
            tl.fromTo('.l4', 3, { width: 0 }, { width: 45 });
            tl.timeScale(4);
        }, 600);
    };
    function largeBlock() {
        setTimeout(function () {
            TweenLite.defaultEase = Linear.easeNone;
            TweenLite.set('.square', { visibility: 'visible' });
            var tl = new TimelineLite();
            tl.fromTo('.l1', 2, { height: 0 }, { height: 227 });
            tl.fromTo('.l2', 3, { width: 0, }, { width: 445 });
            tl.fromTo('.l3', 2, { height: 0 }, { height: 227 });
            tl.fromTo('.l4', 3, { width: 0 }, { width: 445 });
            tl.timeScale(4);
        }, 600);
    }
    function handleScreen(mql) {
        mql.matches ? smallBlock() : largeBlock();
    }
    mql.addListener(handleScreen);
    handleScreen(mql);
    

    Hope this helps. Documentation on CSS media queries can be found here.