Media queries with j-query using match media.

Media Query in JQuery: 
As you know that Media Query was created in CSS. It is used to create responsive web pages. Means that it can display the web contents & layouts in different size of devices with proper format. So, It is widely used to create a user-friendly & mobile-friendly website.In most cases, developers need to add  CSS properties & media Query dynamically to the HTML element using j-Query. To add a media query to the HTML element, You have to write jquery code with the following steps – Create a function responsive(min Width). where min Width is the parameter. Pass a value (min-width: 768px) to the window.matchMedia() and assign it to min Width. Also, Pass min Width to the responsive(min Width). Apply addeventListener with responsive  to the min Width.

Sample code:

// Testing media queries with jQuery
// Using matchMedia

(function($) {

    /*
    * We need to turn it into a function.
    * To apply the changes both on document ready and when we resize the browser.
    */

    function mediaSize() { 
        /* Set the matchMedia */
        if (window.matchMedia('(min-width: 768px)').matches) {
        /* Changes when we reach the min-width  */
            $('body').css('background', '#222');
            $('strong').css('color', 'tomato');

 

        } else {
        /* Reset for CSS changes – Still need a better way to do this! */
            $('body, strong').removeAttr('style');
        }
    };

    /* Call the function */
  mediaSize();
  /* Attach the function to the resize event listener */
    window.addEventListener('resize', mediaSize, false);  

})(jQuery);

Leave a comment

Your email address will not be published. Required fields are marked *