jQuery Plugin For Window.matchMedia API - matchMedia.js
File Size: | 11.6 KB |
---|---|
Views Total: | 2079 |
Last Update: | |
Publish Date: | |
Official Website: | Go to website |
License: | MIT |
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. |
Installation:
# NPM $ 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" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <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 () { $('.js-test1').text('xs'); }, function () { console.log('xs out'); }); $.mq.action('sm', function () { $('.js-test1').text('sm'); }, function () { console.log('sm out'); }); $.mq.action('md', function () { $('.js-test1').text('md'); }, function () { console.log('md out'); }); $.mq.action('lg', function () { $('.js-test1').text('lg'); }, 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:
2018-01-11
- v0.1.1: add option listener
2017-10-17
- 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.