GithubHelp home page GithubHelp logo

wickynilliams / enquire.js Goto Github PK

View Code? Open in Web Editor NEW
3.6K 3.6K 269.0 700 KB

Awesome Media Queries in JavaScript

Home Page: http://wicky.nillia.ms/enquire.js/

License: MIT License

JavaScript 85.31% CSS 4.90% HTML 9.79%

enquire.js's People

Contributors

jorrit avatar nnnnathann avatar peterdavehello avatar samtiffin avatar sboudrias avatar thlorenz avatar wickynilliams 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  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

enquire.js's Issues

browser events not propagated to callbacks

Browser events aren't being propagated all the way up to the callbacks when they are fired as the result of a resize or orientation change.

This is somewhat sucky and totally not cool. Fix this shiznit!

Documentation: MatchMedia.addListener polyfill

This is just something I came up against when initially using the new version in browsers that don't support matchMedia.

You may have already included it in the new docs but it would be good to update the documentation explaining that you also need the matchMedia.addListener polyfill as well as the regular matchMedia one. This caught me out at first.

Removing a function/plugin on unmatch

First off: great little library!

I'm struggling with something which is probably really simple to fix.

I build Mobile first so I only want the JS for non-mobile viewports to be loaded conditionally, I've got that part working fine:

var BPpalm = 'screen and (min-width: 40em)';

enquire.register(BPpalm, [{

    deferSetup: true,

    setup: function setup() {
        var conditionalScript = '/js/conditionally-loaded.js';
        $.getScript(conditionalScript, function() {
            $('.js-menu-accessible-ddown').accessibleDropDownMenu();
        }, true);
    },

    match: function() {
        $('body').css('background', 'gold');
    },

    unmatch: function() {
        $('body').css('background', 'plum');
    }

}]).listen();

What I'm struggling with is that I need to kill the function: accessibleDropDownMenu() for mobile i.e. viewports under 40em which would be the unmatch. Any ideas?

Suggestion: Add example files in documentation

Thank you for an excellent project.

However, the examples in the documentation aren't very beginner friendly. For example, on this page [http://css-tricks.com/enquire-js-media-query-callbacks-in-javascript/], it says:

enquire.register("max-width: 960px", function() { // put Chris' code here to convert your menu to a dropdown });

However, if you copy and paste the Jquery code, nothing happens.
Are you supposed to link to the Jquery file? If so, how would you do that?

It would be nice if you could upload some HTML example pages. (even if it is just something simple like a DIV that changes colour (via Jquery) when you resize the window).

These are great for beginners as they can look at the source code and see exactly how they are supposed to edit the code.

Thanks!

"Not enough arguments" - window.addEventListener

On older browsers like older versions of FF 5 and under, enquire.js kicks an error because there is no useCapture parameter added in the window.addEventListener function.

I get: uncaught exception: [Exception... "Not enough arguments" nsresult: "0x80570001 (NS_ERROR_XPC_NOT_ENOUGH_ARGS)" location: "JS frame :: http://mysite.com/javascripts/enquire.js :: wireFire :: line 364" data: no]

            window.addEventListener(event, function(e) {
                timer && clearTimeout(timer);

                timer = setTimeout(function() {
                    self.fire(e);
                }, timeout);
            });

the third "useCapture" parameter in addEventListener is not an optional in some older browsers. Specifying a value will fix this and allow the script to run without errors on these types of browsers.

issues with opera browser

are you sure this works fine in opera. i'v tested it and it seem to be not working well in opera.

Consider branching when matchMedia listeners are natively supported

Any pitfalls to checking for native matchMedia listener support and, when available, tap into that instead of listening to resize and orientation events? When supported, you should be able to add a listener that will fire when the media query becomes valid or invalid. (See https://developer.mozilla.org/en-US/docs/DOM/MediaQueryListListener for a bit more info, though I think it's more widely supported than that.)

Something like:

if (!window.matchMedia( "" ).addListener) {
    //not natively supported
} else {
    //natively supported
    mql.addListener(function(mql){
        if (mql.matches) {
            //fire match
        } else {
           //fire no match
        }
    });
}

add support for desktop browsers

Hi,

It would be great if this was supported for desktop browsers. I just tried in chrome and it fails, but also this would help me display content better on smaller or browser windows which have changed size

Works perfectly on browser resize, but does not work on phones/tablets

I am using enquire.js to move around elements in the DOM on my smaller-than-desktop screens (tablets and phones).

It works perfectly in a browser (by resizing the window), but it fails to work on phones and tablets.

Here is my code:

$(document).ready(function() {
        enquire.register('screen and (max-width:720px)', function() {
        $('#topnav').insertAfter('#form');
        $('#sidenavbox').insertAfter('.content');
        $('span.speak').text('Tap-to-call:');
        $('#formheader').html('Welcome to CTU! <br />');
        $('#formheader').append($('span.session'));
    });
});

Is there something I am doing incorrectly that is making it work only on desktops?

Always firing all 'unmatch' handlers before 'match' handlers

Hey,

I'm wondering is the following possible. I want all the unmatch handlers to fire first before all the match handlers regardless of the order the handlers are registered.

In my case, I have a component which is a rotator (single item visible) on small views but on larger views becomes a carousel (4 items visible). To handle the transition from one state to another I use the unmatch handler to 'destroy' the plugin and the match handler to initialise the new plugin.

I've found though that when I register multiple handlers the match handlers will run before the unmatch handlers causing problems due to styles still present from the previous state. Ideally I'd like all my unmatch handlers to run before the match handlers to let the new plugin run on a clean slate.

See my below pen. If you look in the console and resize the window, the handlers for the first registered mediaquery always fire first. When going from large to small I'd like unmatch 2 to fire before match 1, and unmatch 1 before match 2 from small to large.

http://codepen.io/anon/pen/zomge

Thanks,
Pat

Enquire.fire() on jQuery Mobile event

Hi Nicky,

For a project i'm combining jQuery Mobile and Enquire. jQuery mobile loads pages through ajax. On the jQuery Mobile "pageshow" event i want to re-evaluate the mediaqueries with Enquire to update the layout of the newly loaded page. But Enquire only fires the first time on "pageshow". If I load a new page it will not fire again, but the pageshow event does get triggered.

I couldn't find how to load another page through ajax on jsFiddle so quickly, but can you take a look? This is the code I use:
http://jsfiddle.net/studiohunto/LQL5w/3/

Thanks in advance,
Lars

How to use respond.js for mobile first, and Enquire, and matchmedia, together?

I am having an issue where if I use respond.js to fix my mobile-first issues for IE 8 & 7, and also load matchmedia for old Android support, and use enquire, it seems that respond.js no longer functions in helping me out with IE 8 & 7 media query support.

I really don't care if enquire does what it's supposed to do in IE 8 and IE 7, I just need to make sure desktop users aren't being served my default "mobile" css.

Any ideas? Have you heard of this issue before? I tried searching the issue queue and found something -similar-, but the answer does not solve my problem (using 'true' for legacy).

media queries

Hey guys,

I have a problem. I designed my website and did not plan to make a mobile version of it relating to ipad and iphone sizes. I then went and designed and implemented my mobile versions as separate sites. The problem I have is linking these separate sites to my current site. How do I do this please?

Match events not firing on devices

Hey Nick,

hopefully I'm just not doing something right but I may have uncovered another issue. This problem only manifests itself on actual devices. It works as expected when in a desktop browser and you resize it.

I've created two testcases in my dropbox which use both the new and old enquirejs (jsfiddle and codepen were inconsistent in their results for some reason) . It seems that the new enquirejs doesn't fire the handlers when on orientation change and moves from one mediaquery to another. I've tested this on a Nexus 7 tablet. I haven't had the chance to test these testcases on an iPad, but I was having the same issue with the site I'm working on iPad where my mediaquery handlers weren't firing on orientation change.

The new experimental branch
https://dl.dropbox.com/u/5894212/enquirejs/new_enquirejs.html

Master branch
https://dl.dropbox.com/u/5894212/enquirejs/old_enquirejs.html

Feel free to grab the files and change them as ye need to.

Thanks,
Pat

enquire.listen doesn't respond on IE9

enquire.register("screen and (max-width:900px)", {

    match : function() {
        console.log("match");
        mediaQueryMatch();
    },
    unmatch : function() {

        console.log("unmatch");
        mediaQueryUnMatch();
    }

}).fire().listen(10);

it does fire once correctly, because i called fire() but it won't be fired on screen resize.

Do not require match(), or at least when setup() is defined

Great solution to replace a similar script of our own! But I do not understand why match() is required, in some situations an empty function is added just to prevent errors.

Example: We have this featured slider. On small screens it only shows titles, on wider screens it also shows images. To prevent the loading of images on small screens we use enquire.js's deferred setup() and do not need match() or unmatch().

A small but welcome enhancement in my opinion.

No unit tests!

Really needs some unit tests, will get them done soon!

How to trigger on load

So there's this note:

A little note: the match or unmatch functions are called if, and only if, a media query's state has changed - that is, matched to unmatched, or unmatched to matched. This is true for both fire and listen.

How, then, do I get enquire to run on page load, the same code that I want to run on a change? Do I put all my code in different functions, and call them once on document.ready with MatchMedia and once in an enquire match? Doesn't seem very DRY. Sorry if this is a noob question.

Responsive images

I stumbled upon your library on CSS Tricks where you mentioned that itโ€™s possible to switch an imageโ€™s src depending on which media query matches by using data-* attributes. Do you have a working example how to use this feature? I couldnโ€™t find anything on your demo page.

v2.0.0 - Error in IE

Hi, first of all thanks for this script. So far I love it with all of my heart!

However, I'm getting the following error in IE (IE 9.0.8112.16421) in Windows 7 (running in a Parallels VM on OSX):

SCRIPT438: Object doesn't support property or method 'addListener'
enquire.min.js, line 5 character 428

This breaks all enquire functionality. I'm using David Knight's media.match.min.js through Modernizr.load() as indicated in your docs, and I can see in the IE dev tools that media.match.min.js is being loaded so it looks to me like that part should be ok. I should note that I'm also using respond.js and my media queries in general are working nicely.

I suspect it's a problem with the matchmedia polyfill (seems like the polyfill just isn't working), so I'll keep plugging away on it and will update here when I crack it.

Thanks for any insight! It's probably something small that I've missed, but it does work beautifully all over OSX & iOS and in better browsers on Windows.

  • Kris

Match and unmatch a jQuery Plugin

Hallo,
i want to use a jQuery Plugin for the Desktop (min-width: 1024px) but not for mobile Devices (max-width: 1024px;) and when the client resize the Browser-window under 1024px width.

I try this, but it doesnยดt work. How can i do this?

$(document).ready(function() {

enquire.register("screen and (min-width:1024px)", {

       match : function() {
        $('#fancy').fancybox({
            openEffect  : 'fade',
            closeEffect : 'fade',
            padding     : 40,
            helpers : { overlay : { css : { 'background' : 'rgba(25,25,25,0.9)'}}}  
        });         
        },
    unmatch : function() {
             $('#fancy').unbind(.fancybox(););
        },  
    setup : function() {},    
    deferSetup : true,          
    destroy : function() {}     
}).listen();

});

Thanks

IE8 issue

Everything is working perfectly in all browsers except IE8.

I added the matchMedia polyfill as outlined on theproject website, and this removed the error from IE's console, but the media queries still do not run.

Any tips to get it functioning in IE8?

Thanks in advance!

Here is js functions to listen window resize !

Is there a way that you use the following js functions and to commit an update of "enquire.js" which would then include a last alternative to listen resize window event before to use the third parameter "shouldDegrade" ? that would be wonderfull ! : )))

Following script work fine on : IE8, Opera 12.12, Chrome 23 and FF 17 !

Just to be inspired :

<head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="initial-scale=1.0, minimum-scale=1.0">

            <script>

            // Global function to attach an event on an element
            function attachEvtHd(elt, evt, hdl, bhr) {
                var locktrigger = false;                
                var locktrigger_ms= 1000;
                var tempotrigger = false;
                var tempotrigger_ms= 100;

                if (elt == null || elt == undefined) return;
                if(elt.attachEvent) {
                    elt.attachEvent(evt, function() {
                        evthd (bhr, hdl);
                        });
                    }
                else if(elt.addEventListener) {
                    elt.addEventListener(evt.replace("on", ""), function() {
                        evthd (bhr, hdl);
                        }, false);
                    }
                else {
                    elt[evt] = function() {
                        evthd (bhr, hdl);
                        };                      
                    }


                // Global function to manage the behaviour of the trigger to call callback function 
                function evthd (behaviour, callback) {
                    if (behaviour == "end") {
                        if (locktrigger !== false) {                        
                            clearTimeout(locktrigger);
                        }
                        locktrigger = setTimeout(function() {
                            window[callback](behaviour);
                        }, locktrigger_ms);
                    }                   
                    else if (behaviour == "live") { 
                        if (tempotrigger == false ) {
                            clearTimeout(tempotrigger);
                            tempotrigger = setTimeout(function() {
                                tempotrigger = false;
                                window[callback](behaviour);
                            }, tempotrigger_ms);    
                        }                       
                    }
                }               
            }

            // Global function to define the client inner size (width or height)
            function getClientSize (sens) {
                if (sens != "Width" && sens != "Height") return;

                var clientSize = 0;
                var fnInnerSens = "inner" + sens;
                var fnClientSens = "client" + sens;

                if (window.window[fnInnerSens]) { 
                    clientSize=window.window[fnInnerSens];
                    }
                else if (document.documentElement) {
                        if (sens == "Width" && document.documentElement.clientWidth) clientSize=document.documentElement.clientWidth;
                        if (sens == "Height" && document.documentElement.clientHeight) clientSize=document.documentElement.clientHeight;
                    }
                else if (document.body) {
                    clientSize=document.body.window[fnClientSens];
                    }
                else return null;
                return clientSize;                  
            }

            function respondHandler (behaviour) {               
                var lastWidth = 0; // = getClientSize("Width");
                var currWidth =  getClientSize("Width");
                var lastHeight = 0; // = getClientSize("Height");
                var currHeight = getClientSize("Height");

                if (currWidth != lastWidth || currHeight != lastHeight) {
                    lastWidth =  getClientSize("Width");
                    lastHeight = getClientSize("Height");

                    }

                    document.forms['eventform'].elements['target'].value=lastWidth + " x " + lastHeight;
                    document.forms['eventform'].elements['event'].value=document.forms['eventform'].elements['event'].value + 1;

            }

            // Apply global function for specific uses :
            attachEvtHd(window, "onresize", "respondHandler", "live");
            // attach "onresize" event on the "window" element with live trigger of respondHandler() function  
            function init() {

                }


            </script>


        </head>

<body>
<form id=eventform>
    BEHAVIOUR = <input type=text name=target>
    <br>
    TRIGGERED = <input type=text name=event>
</form>

</body>

enquire match and unmatch functions on android problem

Hi

This code doesnt seem to work on android browser, but works fine on desktop testing:

$(document).ready(function(){

        //enquire browser width
        enquire.register("screen and (max-width:600px)", {

         match : function() { activateSwipeSlider(); },
         unmatch : function() { console.log('de-activate');  $('h1').css('background-color', '#fff');  } 

        }).listen();

    function activateSwipeSlider() {
          $('h1').css('background-color', '#ccc'); 
        if ( Modernizr.csstransforms ) {
            window.mySwipe = new Swipe(document.getElementById('gallery-list'), {
                startSlide: 1,
                speed: 400,
                callback: function(event, index, elem) {

                // do something cool

                }
            });
        }
    }


});

It doesnt call the 'activateSwipeSlider' function. or anything within the match or unmatch functions.

Am I doing something wrong?

thanks

Have multiple handlers on the same query fire asap.

Would be quite nice to have newly registered handlers that are registered on a query that has already been matched and fired fire immediately.

If it's unclear maybe this fiddle can help.
http://jsfiddle.net/KjtRD/2/

Currently only the first module in that fiddle fires and my wish is to have both fire without any connection to the other. My modules are normally loaded asynchronously with require.js so I cant really just wait for a magical event and then trigger the firing of that media query. Neither can I put listens on all but the last one since I don't know which will be last because they also rely on other conditionals beyond just the viewport size.

Maybe we need to change the way we keep track of fired handlers and put the matched booleans on the handlers themselves.

Modernizr Load and inline JS

Hi Nicky,

Another issue with modernizr. Basically, I'm looking to do this:

Modernizr.load([
        //first test need for matchMedia polyfill
        {
            test: window.matchMedia,
            nope: "assets/js/matchMedia.js"
        },
        //and then load enquire
        "assets/js/enquire.js",
        enquire.register("screen and (min-width:580px)", {
                match : function() {
                    //RUN SOME CODE HERE
                }       
        }, true).listen()
]);

Instead of having to include code in an external file like:

Modernizr.load([
        //first test need for matchMedia polyfill
        {
            test: window.matchMedia,
            nope: "assets/js/matchMedia.js"
        },
        //and then load enquire
        "assets/js/enquire.js",
        "assets/js/enquire_functions.js"
]);

Anytime I place JS directly in that spot it errors and says "enquire is not defined".

If there's a way to run some JS "inline" rather than calling an external script, please let me know how!

Thanks!

Different match and unmatch orders

Match and unmatch functions are triggered in different order when going smaller than going big.
I made this fiddle to compensate my rusty english
http://jsfiddle.net/mjlescano/FmmTa/3/embedded/result/

Tested resizing the window,

reducing the window width the triggers are:
match:bigger
unmatch:bigger
match:normal

making bigger the window, triggers:
match:normal
match:bigger
unmatch:normal

It should be
match:normal
unmatch:normal
match:bigger

Suggestion: "verbose" mode that outputs to the console

This is a great plugin, thanks! My suggestion is to have a "verbose" or logging mode where enquire tells you what's happening with the the match/unmatch/etc functions by safely writing to console.log().

That would save having to put logging statements in each handler.

unmatch-function not executing on page load

Hi!
First of all, thanks for the library, very helpful.
I have the following issue though:

I need to react to the screen size when the page is loaded. Therefore I appended .listen() to my register statement. (I also tried fire() ... same result.)
The match-function gets executed correctly when the page is loaded and the statement is fulfilled.
But for the unmatch-function - it is not executed on page load when the statement is false. Later, when resizing the window, it is executed though.

Is this the intended behaviour? Here is a demo: http://jsbin.com/erehub/1

unregister method, or multiple instances or similar

I'm currently looking at integrating enquire into a Backbone app, but want to allow separate views to control their own media queries... To do so successfully, I need a way to unregister the queries as a view is disposed of.

Would it be possible to add something like this, and/or is it already do-able in the current API and I'm just not seeing it?

Thanks-

Multiple identical media queries bug

Looks like I can't register multiple handlers to the same media query. For example today I tried to do this in my code (actually in two different files) :

enquire.register("screen and (min-width: 780px)", {
    match: foo,
    unmatch: bar
}).listen();

enquire.register("screen and (min-width: 780px)", {
    match: foo2,
    unmatch: bar2
}).listen();

But the second part is never fired. But, if I change 780px by 779px in the second media query for example, it works like it should.

I read one more time your doc and it seems like it should be possible... or am I missing something ?

Thanks.

Fails to install with node v0.9.9, npm 1.2.14

jldupont@jld-desk:~/workspace/some_project/ext/enquire.js$ grunt
Running "lint:prebuild" (lint) task
Lint free.

Running "jasmine" task
Testing jasmine specs via phantom

events.js:69
    throw arguments[1]; // Unhandled 'error' event
                   ^
Error: spawn ENOENT
  at errnoException (child_process.js:922:11)
  at Process.ChildProcess._handle.onexit (child_process.js:713:34)
  at process._makeCallback (node.js:321:24

Uncaught ReferenceError: enquire is not defined

Hi,

Thanks for the great work on enquire.js.

I have this weird problem where my console says Enquire is not defined.
http://cl.ly/image/2l1o470d161W

It occurs in Webkit based browsers. Firefox is fine. IE yet untested.

If I reload a few times sometimes it will load enquire and sometimes it won't. "Sometimes"-bugs are the weirdest to debug unfortunately. If it helps it the error always occurs on first load and then gets fixed after hitting refresh a couple of times.

Also my console reports:

Resource interpreted as Image but transferred with MIME type application/javascript: "http://sitename.dev/js/enquire.min.js". 

MIME type issues are server related (I think) - I use MAMP Pro as the server.

Since my whole JS stack depends on enquire this is breaking the code pretty badly.

I am using the method put forward in the docs

<script src="js/modernizr.min.js" type="text/javascript"></script>
<script>
    Modernizr.load([
        // First test need for polyfill
        {
            test: window.matchMedia,
            nope: "js/polyfills/respond.min.js"
        },

        // And then load enquire
        "js/enquire.min.js"
    ]);
</script>

Later in a file called scripts.js

<script src="js/scripts.js" type="text/javascript"></script>

I'll do something like this:

// Init functions based on media breakpoints
$(function() {

  /*
    @media breakpoints based on SASS vars
    Using enquire JS http://wicky.nillia.ms/enquire.js/

    $breakSmall: > 970px;
    $breakLarge: 970px;
  */

  var breakLarge = "all and (min-width: 970px)";
  var breakSmall = "all and (max-width: 969px)";

  // Functions to be executed on all breakpoints
  initAccordion();
  initJobsSlideshow();

  enquire.register(breakLarge, {
      match : function() {
        // console.log('o hai big screen');
        setContactHeightInit();
        loadBackgrounds();
        navigationCodeBreakLarge();
        initModalBoxes();
      },
      unmatch : function() {
        // console.log('o bye big screen');
      }

  }).listen();

  enquire.register(breakSmall, {
    match : function() {
      // console.log('o hai small screen');
      navigationCodeBreakSmall();
    },
    unmatch : function() {
      // console.log('o bye small screen');
    }
  }).listen();

});

Enquire.js not not triggering on load in Chrome

I haven't had time to make a jsfiddle of this yet, but there seems to be an issue in Chrome v.23 (OS X) where using min and max width queries doesn't work on page load:

enquire.register("screen and (min-width: 800px) and (max-width: 1279px)", {
    match: function() {
        $productsSecondary.equalHeight();
    }
});

enquire.register("screen and (min-width: 1280px)", {
    match: function() {
        $productsRegular.equalHeight();
    }
});

enquire.listen();

It works in Firefox and Safari 6 though. Resizing the window to transition to a different breakpoint will cause Chrome to finally trigger the functions in enquire.register().

Just wondering if I'm missing something here about using both min and max-width queries in a single query.

Great plugin though! Works a lot better generally than my old hacks.

IE9 & backstretch.js

Hi there, my code is pretty basic and I'm just wondering whether I just got lucky in most browsers or whether there are any issues with IE9.

So, here is my code:

<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script> <script src="js/enquire.min.js" type="text/javascript"></script> <script src="js/jquery.backstretch.min.js" type="text/javascript"></script> <script> $(document).ready(function($) { enquire.register("screen and (min-width:768px)", { match : function() { $.backstretch("img.jpg"); // img that fits the body of the browser } }).listen(); }); </script>

This has the desired effect when tested using Chrome, Firefox, Safari and on my HTCs in that if the viewport is less than 768px when loading then there is no image. However IE9 does not load the background image no matter what the situation. For reference, if I "//" out the enquire.js code from the script, so that it just becomes...

<script> $(document).ready(function($) { $.backstretch("img.jpg"); // img that fits the body of the browser }); </script>

...then this works.

Apologies if I have made any fundamental errors or if there is a simpler way to do this, I'm a bit of a noob and this is my first ever post on github.

Thanks,
Mark (also in Wales, UK)

media query match problem

I build a little demo page which change background-color in dependency of media query. Here's a css:

body {
    padding:0;
    margin:0;
    background-color:yellow;
}
@media screen and (max-width: 768px) {
    body {
        background-color:green;
    }
}
@media screen and (max-width: 480px) {
    body {
        background-color:red;
    }
}

Now i want to match queries with enquire.js and log background-color:

enquire.register("screen and (max-width: 480px)", {
    match: function () {
        console.log('red')
    }
}).register("screen and (max-width: 768px)", {
    match: function () {
        console.log('green')
    },
    unmatch: function () {
        console.log('yellow')
    }
}).listen(10);

It works, but not in the case when you go from 'red' to 'green'. Seems like a problem with query matching.

Any suggestions?

Match not firing on Kindle Fire

I'm using enquire to move elements around the DOM only when in responsive mode. I noticed that on some devices, with my original code, it would not reset the elements to their original location when shifting from portrait to landscape mode and thus moving from the mobile to the desktop queries. So I decided to use the match and unmatch functions to take care of this. (Disclaimer: yes, I am using a matchmedia polyfill) It works well in Android, but match and unmatch do not work in the Kindle Fire for some reason.

Original code:

$(document).ready(function() {
        enquire.register('screen and (max-width:720px)', function() {
        $('#topnav').insertAfter('#form');
        $('#sidenavbox').insertAfter('.content');
        $('span.speak').text('Tap-to-call:');
        $('#formheader').html('Welcome to CTU! <br />');
        $('#formheader').append($('span.session'));
    });
});

Code with Match and Unmatch:

$(document).ready(function() {
    enquire.register('screen and (max-width:737px)', {

        match : function() {  
        $('#topnav').insertAfter('#form');
        $('#sidenavbox').insertAfter('.content');
        $('span.speak').text('Tap-to-call:');
        $('#formheader').html('Welcome to CTU! <br />');
        $('#formheader').append($('span.session'));
        },
        unmatch : function() {
            window.location.reload();
        }

    });
});

Do you see any reason as to why it would work on desktop and in Andriod phones but not on the Kindle?
I've also tried this with destroy, but that doesn't work for desktops.

Simplify conditional asset loading

Whilst conditional one-time asset loading is possible via the setup callback, it's not ideal as you have to write boilerplate code. Tighten up the API to make this easier to handle. Consider something along the lines of:

enquire.register("screen and (min-width: 500px)", {
    setup : [
        //tie in with Modernizr.load/yepnope
        'some-file.js',
        'some-file.css'
    ]
});

Respond.js like triggering of queries for legacy browsers

Hi!

First I'd like to thank you for your great plugin - it's working really well!

I wanted to set this as a suggestion or request - but really an issue but I couldn't find it. Sorry about that.

I know this topic has been touched many times in many preview issues - but I wanted to ask you if this was possible.

For browsers like IE8 - that don't support media queries - the matchMedia queries won't fire. One way is of course - to use the shouldDegrade parameter - to make sure at least of one the queries fire.

I am using media queries in css and Respond.js as a polyfill and it's actually working fine in legacy browsers - the media queries are triggering. It made me curious and I checked the code for an explanation.

Apparently there is a listener on window resize and it checks if the size changed so that any of the media queries matches would change - and fires from here.

Would it be possible to have this kind of support for the older browsers? I.e. - have the possibility to add a window resize listener that triggeres the queries manually. I know that you are all for that nice and lean code, and it would probably add some lines to it.

What do you think? See the bottom of https://github.com/scottjehl/Respond/blob/master/respond.src.js

Thanks again!

Resize browser window problems

Hi, I've created this code:

<script language="javascript" type="text/javascript">
    var $body = jQuery('body');

    enquire.register("(min-width: 961px)", {
        match: function() {
            $body.addClass("large");
        },
        unmatch: function() {
            $body.removeClass("small medium");
        }
    });

    enquire.register("(min-width: 701px) and (max-width: 960px)", {
        match: function() {
            $body.addClass("medium");
        },
        unmatch: function() {
            $body.removeClass("small large");
        }
    });

    enquire.register("(max-width: 700px)", {
        match: function() {
            $body.addClass("small");
        },
        unmatch: function() {
            $body.removeClass("medium large");
        }
    });

    enquire.listen(20, true)
</script>

Everything works correctly, but if I resize my browser window, new class and old classes aren't managed well.
What I need is "cutting" width in 3 steps:

  • more than 960px (large)
  • more than 701px and less than 960px (medium)
  • less than 700px (small)

I want add a new class responsively to the real actual width of window and, at the same time, if I decide to resize window I want that uncorrect classes are killed and new one is correctly inserted for my BODY element.

Example:
resizing my browser window from 950px to more than 960px I'd expect this:

  • BODY has a new class: large
  • BODY hasn't more two classes: medium and small

What is wrong in my code?
Thanks a lot!

shouldDegrade doesn't work on IE8 nor Opera

The third parameter "shouldDegrade" doesn't work on IE8 nor Opera 12.12

js files matchMedia + enquire appear well as downloaded by IE8.
No error appear in the IE8 console.

Note : The same page work fine with Chrome 23 and FF 17 !

Thanks by advance for your help : )

Using breakpoints from CSS

Hoi,

would it be possible to read/get the media queries/breakpoints which are defined in CSS?

Some kind of a clever method I've found on the blog of Jeremy Keith, refering to the blog
of Andy Rossi, who uses the after pseudo element to populate media query states:
http://adactio.com/journal/5429/

The key of this 'mechanism' is to get rid of duplicate media query definitions.
And in JS it's possible to address the media queries using an identifier/key.

Would it be possible to use enquire.js to listen on this
somehow, without redefining the media queries?

Match not firing on page load

Hey Nicky,

I've been trying out this experimental branch but I think I've found an issue. Matches don't fire by default when the page loads when the page is within a mediaquery. I've created a demo here. You should get a log of match in the console but it doesn't fire.

I've narrowed it down to this line in the code

Line 103
!this.initialised ? this.setup() : this.options.match();

if initialised is false this.options.match() never runs. I swapped it for the code from the current stable version and the match correctly fired on page load.

if(!this.initialised){
   this.setup(e);
}
this.options.match(e);

Am I missing something or is this a bug?

Thanks,
Pat

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.