by
back

Responsive Javascript with enquire.js

Since we all use mediaqueries to get responsive webdesigns there is a need for responsive javascript as well. Especially when it comes to showing and hiding elements on your website, loading content to your site of a specific media query matches or just to add some nice little feature to your code.

Thanks to Nick Williams we can now use responsive javascript out of the box. Check his pure Javascript library enquire.js and get started in seconds.

How to get started with enquire.js

Step 1: Download and save enquire.min.js to your website project

Step 2: Add the library downloaded in step one to your documents head-section.

<script src="javascripts/enquire.min.js"></script>

Step 3: Add a custom javascript file to your documents head-section. In this case named as application.js

<script src="javascripts/application.js"></script>

Step 4: Copy and Paste this code to get started with enquire.js

enquire.register("screen and (max-width:45em)", {

    // OPTIONAL
    // If supplied, triggered when a media query matches.
    match : function() {},      

    // OPTIONAL
    // If supplied, triggered when the media query transitions 
    // *from a matched state to an unmatched state*.
    unmatch : function() {},    

    // OPTIONAL
    // If supplied, triggered once, when the handler is registered.
    setup : function() {},    

    // OPTIONAL, defaults to false
    // If set to true, defers execution of the setup function 
    // until the first time the media query is matched
    deferSetup : true,

    // OPTIONAL
    // If supplied, triggered when handler is unregistered. 
    // Place cleanup code here
    destroy : function() {}

});

check Nick Williams site to get all those information and details.

Example: Showing and hiding parts with jQuery and enquire.js

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

    match : function() {
    $("nav.mobile-navigation").show();
    }, 

    unmatch : function() {
        $("nav.mobile-navigation").hide();
    }

});

Example: showing your mobile navigation based on the screensize width of 768px and hiding it if screensize is larger than 768px.

I'm using it in a couple of projects and can't report any problems like performance issues.

That's all you need to know I hope.

Cheers,
Flo

comments powered by Disqus