jQuery Plugin For Window.matchMedia API - matchMedia.js

File Size: 11.6 KB
Views Total: 1937
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
jQuery Plugin For Window.matchMedia API - matchMedia.js

matchMedia.js is a jQuery plugin for Window.matchMedia() web API that allows you to execute custom functions when the screen size matches the specified media query string.

 The Window.matchMedia() API returns a new MediaQueryList object representing the parsed results of the specified media query string.


$ npm install jquery-matchmedia --save

How to use it:

1. Insert the jquery.matchMedia.min.js or jquery.matchMedia.polyfill.min.js (include polyfill) after jQuery JavaScript library and you're ready to go.

<script src="//code.jquery.com/jquery-3.2.1.slim.min.js" 
<script src="jquery.matchMedia.js"></script>

2. Set the media query rules in the JavaScript or CSS as follows:

$.mq.action('(min-width: 40em)');
html:before {
  display: none;
  content: '{"xs" : "(max-width: 47.9375em)", "sm": "(min-width: 48em) and (max-width: 61.9375em)", "md": "(min-width: 62em) and (max-width: 74.9375em)", "lg": "(min-width: 75em)"}';

3. Execute your own functions when the media query rules are true or false.

$.mq.action('xs', function () {
}, function () {
  console.log('xs out');

$.mq.action('sm', function () {
}, function () {
  console.log('sm out');

$.mq.action('md', function () {
}, function () {
  console.log('md out');

$.mq.action('lg', function () {
}, function () {
  console.log('lg out');

$('.js-test2').mq('(max-width: 900px)', function () {
  $(this).css('color', 'green').text('@media (max-width: 900px) { true }');
}, function () {
  $(this).css('color', 'red').text('@media (max-width: 900px) { false }');

Change log:


  • v0.1.1: add option listener


  • change use css breakpoints

This awesome jQuery plugin is developed by dkacha. For more Advanced Usages, please check the demo page or visit the official website.