GPS

Breakpoint situational awareness

Have you ever needed to know within JavaScript what CSS breakpoint state is active? I know I sure have. GPS dispatches an event when the browser enters a new breakpoint state, useful for starting up or tearing down scripts that should only run on specific device sizes.

DemoDownloadGithub


What it does

GPS sets a global variable, so you can identify the current the breakpoint state. The variable is updated after page load and browser resize. You can subscribe to the event to catch updates to the browser width.


Usage

1. Include the Script


«script src="jquery.js"»«/script»
«script src="jquery.gps.js"»«/script»

2. Instantiate the Script


$.gps();

3. Check GPS

console.log( window.gps );

if ( window.gps == "mobile" ){
//mobile
} else if ( window.gps == "tablet" ){
//tablet
} else {
//desktop
}

4. Subscribe to GPS change event


$(document).bind("gps", function(e) {
console.log( 'GPS changed to: '+window.gps );
}


Options

GPS takes one parameter – breakpoint – an object containing key/value pairs for breakpoint state and minimum width. The value is the equivalent of the media query min-width, and comes from the browser visible screen width.

The default settings:


var defaults = {
'mobile': 0,
'tablet': 640,
'small-desktop': 960,
'full-desktop': 1140
}
$.gps({ 'breakpoints': defaults });

You can specify your own custom breakpoint parameters.


var custom_breakpoints = {
'tamagotchi': 0,
'mobile': 100,
'tablet': 480,
'desktop': 960
}
$.gps({ 'breakpoints': custom_breakpoints });

In this example 0-639 registers as ‘mobile’, 640-959 as ‘tablet’, etc.

{ 'mobile': 0, 'tablet': 640, 'desktop': 960 }

Event


//bind to event
$(document).bind("gps", function(e) {
//check state
if (window.gps == 'mobile'){
//state is mobile
}
});


Notes

Viewport

You’ll need to add the meta viewport tag for mobile devices to respond correctly without resizing the page.


«meta name="viewport" content="width=device-width, initial-scale=1" /»


Dependencies

jQuery
SmartResize (included)


DemoDownloadGithub