• Stars
    star
    137
  • Rank 260,754 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated about 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

matchmedia wrapper for angularjs

matchmedia-ng

matchmedia-ng is a set of AngularJS bindings and helper functions for the matchMedia javascript api. With matchMedia, AngularJS and matchmedia-ng you can automatically respond to the orientation, browser height, width and other properties supported by CSS Media Queries.

matchmedia-ng provides two core methods .is() and .on.

.on() is syntactically similar to the angular .$on() method, providing a way to listen on media queries and respond. .is() is just a simple alias for the matchMedia().matches method.

Both on() and is() have aliases provided for the following common media queries:

  • print - print
  • screen - screen
  • phone - (max-width: 767px)
  • tablet - (min-width: 768px) and (max-width: 979px)
  • desktop - (min-width: 979px)
  • portrait - (orientation: portrait)
  • landscape - (orientation: landscape)

They can be used as onPrint(), isPortrait(), onLandscape() etc.

Live Demo: AngularJS Media Query App.

Check out the github-pages branch for more the live demo code.

Install

bower install matchmedia-ng

Usage

Include angular.js and mediastore-ng.js in your application. Optionally you can include the matchMedia polyfill if are worried about browser compatibility

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="matchmedia.js"></script>
<script src="matchmedia-ng.js"></script>

Add the module matchmedia-ng as a dependency to your app module:

var myapp = angular.module('myapp', ['matchmedia-ng']);

Quick Start

Set matchmedia as a service dependency in your controller:

myapp.controller('MyCtrl', ['$scope', 'matchmedia',
  function MyCtrl($scope, matchmedia) {
    ...
  }
]);

If you would like to execute javascript code to load a higher resolution image when the page loads on a tablet rather than a mobile phone, you could do something like the following in your controller:

$scope.tablet = matchmedia.isTablet();
if($scope.tablet){
	$scope.primaryImg = "images/[email protected]";
}

If you would like to do something a bit more complicated, such as detect when the user drags the page below the threshold of a mobile phone, you can do something like this:

var unregister = matchmedia.onPhone( function(mediaQueryList){
  $scope.isPhone = mediaQueryList.matches;
});

Or even execute javascript when the user attempts to print the page.

var unregister = matchmedia.onPrint( function(mediaQueryList){
  $scope.isPrint = mediaQueryList.matches;
  //hide ads, show water mark, pause animations/video, etc.
});

See the source for the controller behind the demo app for a working example code.

Custom Media Queries

Though the common media query aliases are helpful, in some cases you will want to execute javascript on very specific media queries (maybe in tandem with a specific css media query). In that case you can use the core .on() and .is() functions;

on()

/**
 * @param {string} query Media query to listen on.
 * @param {function(mediaQueryList)} listener Function to call when the media query is matched.
 * @param {$scope} $scope Optional AngularJS scope, if not provided will use $rootScope
 * @returns {function()} Returns a deregistration function for this listener.
 */
matchmedia.on(query, listener, $scope)


matchmedia.on('tv and (min-width: 700px) and (orientation: landscape)', function(mediaQueryList){
	console.log(mediaQueryList.matches);
})

is()

/**
 * @param {string} query media query to test.
 * @returns {boolean} Returns true if the media query matches.
 */
matchmedia.is(query)

var resp = matchmedia.is('(min-width: 700px), handheld and (orientation: landscape)');

Aliases & Shortcuts

The following is a comprehensive list of the media query aliases.

matchmedia.onPrint(listener, $scope)
matchmedia.onScreen(listener, $scope)
matchmedia.onPhone(listener, $scope)
matchmedia.onTablet(listener, $scope
matchmedia.onDesktop(listener, $scope)
matchmedia.onPortrait(listener, $scope)
matchmedia.onLandscape(listener, $scope)

matchmedia.isPrint()
matchmedia.isScreen()
matchmedia.isPhone()
matchmedia.isTablet()
matchmedia.isDesktop()
matchmedia.isPortrait()
matchmedia.isLandscape()

Override Aliases

It is possible to override the media queries given for the aliases above by using a config function.

angular.module('myapp', ['matchmedia-ng']).config(['matchmediaProvider', function (matchmediaProvider) {
      matchmediaProvider.rules.phone = "(max-width: 500px)";
      matchmediaProvider.rules.desktop = "(max-width: 1500px)";
   }]);

Logging

You can enable logging by using the following snippet in your code.

    .config(['loggerProvider',function(loggerProvider){
        loggerProvider.setDEVMODE(true);
    }])

TODO

  • Add more documentaton regarding the matchmedia queries. (full options list).
  • Example with polyfill.
  • Tests for the matchmedia-ng framework are coming shortly.

Pull Requests

To make a pull request, please do the following:

Mention what specific version matchmedia-ng.js you were using when you encountered the issue/added the feature. This can be accessed by looking at the matchmedia-ng.js file header. Provide a pastie or gist that demonstrates the bug/feature Do not modify the version header. I will modify that manually when merging the request

License

Copyright (c) 2013 Jason Kulatunga, released under the MIT license

More Repositories

1

scrutiny

Hard Drive S.M.A.R.T Monitoring, Historical Trends & Real World Failure Thresholds
Go
4,678
star
2

lexicon

Manipulate DNS records on various DNS providers in a standardized way.
Python
1,454
star
3

gitmask

Contribute Code Anonymously
Python
449
star
4

hatchet

Cut down spam in your Gmail Inbox
Go
362
star
5

dropstore-ng

Dropbox Datastore bindings for AngularJS
JavaScript
243
star
6

drawbridge

manage SSH access to multiple applications/environments protected by bastion servers
Go
219
star
7

capsulecd

Continuous Delivery for automating package releases (npm, cookbooks, gems, pip, jars, etc)
Go
96
star
8

docker-cron

`cron` base images for various distros.
Dockerfile
82
star
9

justvanish

Tell databrokers to F#@% Off. Your data is your data, they shouldn't be monetizing your personal information without your knowledge.
Go
69
star
10

you-dont-know-jenkins-init

Groovy
58
star
11

lantern

Peer into your requests.
Go
23
star
12

aws-api-gateway-letsencrypt

AWS Api Gateway Custom Certificates using Letsencrypt
Python
20
star
13

you-dont-know-jenkins

Code/Snippets for Jenkins Automation blog post.
Ruby
20
star
14

goodreads.js

GoodReads NodeJS API
JavaScript
12
star
15

zRSSFeed

zRSSFeed by Zazar, modified to support multiple RSS Feeds
JavaScript
11
star
16

DeDRM.Net

No Longer Maintained, use https://github.com/apprenticeharper/DeDRM_tools
Python
11
star
17

Wix3.6Toolset

WixToolset 3.6 RC0 Branch + Client Tools DLL
C#
9
star
18

tentacle

Retrieve your secrets from wherever they live. Vault/Cyberark/Thycotic/Keychain/Keyring/etc.
Go
8
star
19

quietthyme.plugin

Quietthyme Calibre Plugin
Python
8
star
20

letsencrypt-http01-docker-nginx-example

Dockerfile which automates Letsencrypt using Nginx
Shell
7
star
21

you-dont-know-jenkins-job-dsl

Jenkins Job DSL example for "You Dont Know Jenkins" blog series
Groovy
7
star
22

bedrock

Dockerfile
7
star
23

pubsub-emitter

sails socket hook to communicate with a standalone socket.io server.
JavaScript
5
star
24

docker-jenkins-inbound-agent-runtimes

Language specific Jenkins inbound agent containers. See https://github.com/jenkinsci/docker-inbound-agent/
Dockerfile
4
star
25

GoodReadsSharp

GoodReadsSharp is a C# client library for the GoodReads API. Used to power QuietThyme.com goodreads authentication and integration.
C#
4
star
26

pouchdb-ng

PouchDB AngularJS Bindings
JavaScript
3
star
27

Iris

in browser epub + mobi ebook viewer,powered by monocle + js-epub
JavaScript
3
star
28

web-zipper

Online Zip File generator. Will generate a zip file when given a list of urls.
2
star
29

obscenity

generic password retrieval library
2
star
30

novel-concepts

2
star
31

Veil

Angular Application that allows you to securely encrypt and retrieve your SSH keys from Dropbox storage.
JavaScript
2
star
32

go-util

utility functions for go.
Go
2
star
33

docker-hub-matrix-builds

Test repo for docker hub matrix builds. See https://blog.thesparktree.com/docker-hub-matrix-builds
Shell
2
star
34

sunlight

Expose your Keystore (or Keychain) secrets as environmental variables.
Go
1
star
35

you-dont-know-jenkins-dynamic-kubernetes-slaves

Setting up a Jenkins + Kubernetes lab environment.
Dockerfile
1
star
36

jquery-unison

JQuery Plugin that aggregates multiple Google Calendars
JavaScript
1
star
37

scrutiny_windows_test

Dockerfile
1
star
38

node-angular-less-seed

NodeJS + AngularJS + EJS Templates + Bootstrap/Less Seed
JavaScript
1
star
39

lucid-wix

Lucid-Wix is a C# library that creates fluent bindings to Wix 3.7
C#
1
star
40

flywheel

Preserve your productivity. Setup scripts for your new Mac.
Shell
1
star
41

sails-passport-authentication

Sails 0.9.x example using passport authentication, Google, LinkedIn, Facebook, Twitter.
JavaScript
1
star
42

sails-helm

Sails.js activeadmin style administration application.
1
star
43

share-plates-beta

JavaScript
1
star
44

recall

Google Chrome extension for Mozilla SyncServer
1
star
45

you-dont-know-jenkins-configuration-as-code

Dockerfile
1
star
46

jason-is-baller

The source for JasonIsABaller.com
1
star
47

kickback

Generates a Google Sheet that can be used to easily split trip expenses between friends. Based on Chi's amazing Owing Sheet.
JavaScript
1
star
48

banditio.engine

Python websocket server implementing the bare minimum Chrome Remote Debugging Protocol (all notifications are pushed via the banditio.proxy)
Python
1
star
49

docker-consul-template-haproxy

forked/merged from https://github.com/bluk/docker-consul-template-haproxy-app and https://github.com/bluk/docker-consul-template-haproxy
Shell
1
star
50

npm_analogj_test

Test npm package for use with capsulecd.
JavaScript
1
star