During customization or custom solutions development in Magento 2, you may have some scenarios where you need to manipulate JavaScript for the desktop or mobile view. For example, performing some action on a specific desktop and mobile screen size.

In this article, we will show you how to use Media queries in Magento 2 JavaScript.

Media Queries In JavaScript

Magento 2 out of the box comes with a built-in library called matchMedia.js. You can call the mediaCheck() function from matchMedia.js to manipulate JavaScript for the desktop or mobile view.

mediaCheck function is a simple wrapper around matchMedia to run code on entry and exit from media queries. Also, it uses browser resize as a fallback for browsers that don’t support matchMedia.

Using In JavaScript File

1. view/frontend/web/js/our-media-queries.js :

define([
    'jquery',
    'matchMedia'
], function ($, mediaCheck) {
   'use strict';
    mediaCheck({
        media: '(min-width: 768px)',
        // Switch to Desktop Version
        entry: function () {
            /* Your function goes here */
	    console.log('starting 768');			
        },
        // Switch to Mobile Version
        exit: function () {
            /* Your function goes here */
	    console.log('leaving 768');			
        },
        // Mobile and Desktop Versions
        both: function () {
            /* Your function goes here */
	     console.log('changing state');			
        }		
    });
});

Using In PHTML File

1. view/frontend/templates/our-media-queries.phtml

<script type="text/x-magento-init">
    {
    "*": 
        {
            "Vendor_Module/js/our-media-queries": {}
        }
    }
</script>

2. view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            ourMediaQueries: 'Vendor_Module/js/our-media-queries'
        }
    }
};

3. view/frontend/web/js/our-media-queries.js

require([
    'jquery',
    'matchMedia'
], function ($, mediaCheck) {
   'use strict';
    mediaCheck({
        media: '(min-width: 768px)',
        // Switch to Desktop Version
        entry: function () {
            /* Your function goes here */
	    console.log('starting 768');			
        },
        // Switch to Mobile Version
        exit: function () {
            /* Your function goes here */
	    console.log('leaving 768');			
        },
        // Mobile and Desktop Versions
        both: function () {
            /* Your function goes here */
	     console.log('changing state');			
        }		
    });
});

replace: Vendor\Module with your vendor and module name

mediaCheck Options

Here are media check options you can use in media, entry, exit, and both functions:

media

  • Type: string
  • example of mediaquery that will trigger the specified action: (min-width: 420px), (min-width: 35em), (max-width: 800px), (max-width: 60em).  You can use any screen size you need there, eg. (min-width: 768px), etc.

entry

  • Type: function
  • Params: mq (the media query object. eg. "entry: function (mq) {}")

The entry function will execute once when the media query becomes active.

exit

  • Type: function
  • Params: mq (the media query object. eg. "exit: function (mq) {}")

The exit function will execute once when the media query becomes inactive.

both

  • Type: function
  • Params: mq (the media query object. eg. "both: function (mq) {}")

The both function will execute once when the media query changes state.

Conclusion

We hope you find this guide to "use media queries in Magento 2 JS" helpful. Feel free to share or leave a comment below. Your opinion is much appreciated!

If you're looking for experienced Magento 2 developers to customize your site, fix issues, develop custom solutions, or anything else, feel free to check on this collection of Quality Services For Magento 2, choose the service that best suits your needs, or contact us

Tags: magento-2-frontend-development