wiggle
Subscribe and react to page breakpoints.
Ideal for responsive pages as it allows us to easily react with JS on page layout changes.
When to use it
- We might need to swipe position of 2 elements with JS/jQuery when page layout changes from desktop to mobile layout and vice versa
- We want to optimize code to include only components that are used on current screen layout (in React, Vue, Angular...). Check "examples of usage in Vue.js" at the bottom for more info
- We might want to optimize page to load additional resources only if layout is desktop.
- In any other case when we want to execute custom JS code on specific page layout.
var wiggle = Wiggle.init([{
minWidth: 992,
name: 'desktop'
}, {
minWidth: '768',
maxWidth: '62em',
name: 'tablet'
}, {
maxWidth: 767,
name: 'mobile'
}]);
wiggle.on('mobile', function() {
console.log("Function that will be executed if current screen size is mobile and every time screen sizes switches to mobile");
});
wiggle.on('mobile', function() {
console.log("We can have multiple listeners for same screen size and each will be executed.");
});
wiggle.on('desktop', function() {
console.log("Function that will be executed if current screen size is mobile and every time screen sizes switches to mobile.");
});
wiggle.queueOn('mobile', function() {
console.log("function that will be executed every time screen sizes switches to mobile size");
});
wiggle.off('mobile', function() {
console.log("function that will be executed if screen size is not mobile and every time screen size stops being mobile");
});
wiggle.queueOff('mobile', function() {
console.log("function that will be executed every time screen size stops being mobile");
});
if(wiggle.is('desktop')) {
console.log("Current screen size is desktop");
}
Examples of usage in Vue.js
Basic premises is that we will have components that will need to be displayed only on desktop.
We can easily hide them with media-queries and display none. Problem with hiding them like that is that components will
still render and components code will still be executed which is far from ideal.
With wiggle and v-if directive we can easily optimize that and render only components that are actually used on current screen layout.
wiggle.on('desktop', () => store.dispatch('changeViewType', View.type.DESKTOP));
wiggle.on('tablet', () => store.dispatch('changeViewType', View.type.TABLET));
wiggle.on('mobile', () => store.dispatch('changeViewType', View.type.MOBILE));
computed: {
isDesktop() {
return this.$store.state.App.view.type === View.type.DESKTOP;
}
}
The above code allow us to do something like
<widgets-sidebar v-if="isDesktop"><widgets-sidebar>
Supported browsers
Wiggle is using matchMedia to detect layout changes.
If you need to support browser that does not support matchMedia (IE9 and below) you need to include matchMedia polyfill before using this library.