Magento2 – Using Media Queries in JavaScript

magento2

Does Magento2 comes with enquire.js? How can we use media queries in JavaScript similar to enquire.js in Magento1.

Best Answer

Magento 2 DevDocs states the following:

/*...*/
mediaCheck({
    media: '(min-width: 768px)',
    // Switch to Desktop Version
    entry: function () {
        /* The function that toggles page elements from desktop to mobile mode is called here */
    },
    // Switch to Mobile Version
    exit: function () {
        /* The function that toggles page elements from mobile to desktop mode is called here*/
    }
}); /*...*/

Magento 2 uses require.js, an easy way to add media queries in JavaScript in a .phtml file would be done by:

<script type="text/javascript">
    require([
        "matchMedia",
    ], function (mediaCheck) {
        "use strict";

    mediaCheck({
        media: '(min-width: 768px)',
        // Switch to Desktop Version
        entry: function () {

        },
        // Switch to Mobile Version
        exit: function () {

        }
    });
}
</script>
Related Topic