Giter Site home page Giter Site logo

matchmedia-ng's Introduction

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.

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

matchmedia-ng's People

Contributors

analogj avatar bryant1410 avatar capsulecd avatar domicode avatar gsong avatar izifortune avatar segeek avatar websirnik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

matchmedia-ng's Issues

DEVMODE should be false by default

Currently a config block is used to activate DEVMODE within the matchmedia-ng module. This forces the application owner to explicitly turn DEVMODE off by utilizing a separate config module at the application level. This additional config block will always be needed for production instances where logging should be turned off.

I suggest removing the config block within matchmedia-ng and allowing the application developer the option to add a config block at the application level instead.

IE9 Object doesn't support property or method 'matchMedia'

I'm getting this error in IE 9. In all other browsers it's working.

I have this in my main controller

matchmedia.onLandscape(function(mediaQueryList){
if(mediaQueryList.matches){
$("html").removeClass("portrait").addClass("landscape");
}
});
matchmedia.onPortrait(function(mediaQueryList){
if(mediaQueryList.matches){
$("html").removeClass("landscape").addClass("portrait");
}
});

Typo in doc ('Override Aliases')

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

should be:

matchmediaProvider.rules.desktop = "(max-width: 1500px)";

(no ':' after .desktop)

xl browser size

Is there a way to add a variable for an xl browser size without editing the match-media.js file directly?

eg.

var defaultRules = {
xl : '(min-width: 1600px)',
lg : '(min-width: 1200px) and (max-width:1599px)',
md : '(min-width: 992px) and (max-width: 1199px)',
sm : '(min-width: 768px) and (max-width: 991px)',
xs : '(max-width: 767px)'
};

to clever when ask for printing

Hi.
When I ask for a print with google chrome (using $window.print, not with ctrl+p), it open the print preview (ok, normal behaviour).
At opening, lib is so clever, it analyse the new screen (the print preview one) and send event to application saying it's mobile format. this result by changing the website behind the print preview window.

Is there a way to avoid this to smart detection?
using google chrome on MAC

Feature: matchmedia directive

It would be useful to use matchmedia-ng as a directive.

An example with a custom media query (adapted from the README) could then be rewritten entirely in the template (pseudo-code):

<matchmedia ng-model="tablet" is="(min-width: 768px) and (max-width: 979px)"></matchmedia>
<img ng-src=""images/[email protected]" ng-if="{{tablet}}"/>

This feature was inspired by the Polymer core-media-query element.

.on function trigerred at wrong time

Hi there,

I just tried to play a bit with the lib and here is my setup:

In app.config I added the following custom rules:

matchmediaProvider.rules.phone = "(max-width: 799px)";
matchmediaProvider.rules.desktop = "(min-width: 800px)";

Then in my directive controller I have this:

                    matchmedia.onPhone(function() {
                            console.log("PHONE");
                        });

                    matchmedia.onDesktop(function() {
                            console.log("DESKTOP");
                        });

Result is that I get both PHONE and DESKTOP in the console at each transition between the states, meaning when I go under 800px and when I go above it. I expected to get PHONE when going under and DESKTOP when going above.
For the record, I also tried with the .on function and passing the "max-..." param and I get the same result.

There is no exception raised or errors in the console and setting the dev mode did not really gave much info besides:
["Creating matchmedia"]
["adding listener for query: (max-width: 799px)"]
["adding listener for query: (min-width: 800px)"]

I am using it wrong?

Thanks,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.