Enquire.js for Responsive JavaScripting

Responsive web design is all the rage lately, and with good cause. With the plethora of devices and screen sizes and aspect ratios, you can’t create a “desktop” site and a “mobile” site anymore. The best approach is to create one site that adapts to fit the device it is being viewed on. CSS media queries make it dead simple to style every element on a page exactly how you want at any screen size.

But what about JavaScript? I have some fancy jQuery animation that happens when a user clicks a button. It looks sweet on a desktop. But it’s kind of awkward on phone. Actually, it just looks bad and is pointless on a mobile device. If only I could add JavaScript to those CSS media queries. Wait. I can.

Enquire.js is a lightweight JavaScript library for handling media queries. It works almost the same way as CSS media queries, you specify the max- or min-width and give it some commands to execute. More good news: it has no dependencies, not even jQuery! It’s pure JavaScript awesomeness.

Enquire gives you the option to execute code when your specified media query is matched or unmatched, meaning it listens for viewport changes and can execute different code as the window changes size. Here’s the basic setup:

1
2
3
4
5
enquire.register("screen and (max-width:1024px)", {
match: function() {
console.log("handler max-width 1024px");
}
}).listen();

 

Simple. And it just works. Need multiple queries? Not a problem:

1
2
3
4
5
6
7
8
9
enquire.register("screen and (max-width:1024px)", {
match: function() {
console.log("handler max-width 1024px");
}
}).register("screen and (max-width:480px)", {
match: function() {
console.log("handler max-width 480px");
}
}).listen();

Read more about it here.

CSS-Tricks also has good write-up about Enquire.js

Leave a Reply