Breakpoint.js

by michaelhue

JavaScript

(function(window) {

var Breakpoint = {

    _breakpoints: {},
    
    _current: null,
    
    /*
    Function: update
    
    
    
    */
    update: function() {
        for (var breakpointWidth in this._breakpoints) {
            if (window.innerWidth <= breakpointWidth) {
                if (breakpointWidth === this._current) {
                     return;  
                }
                if (this._current !== null && typeof this._breakpoints[this._current].onLeave === 'function') {
                    this._breakpoints[this._current].onLeave();
                }
                
            }
        }
    },
    
    /*
    Function: at

    Registers a new breakpoint handler with a required callback for entering and
    an optional callback for leaving the breakpoint.
    
    Parameters:
        - width: A width in pixels defining the breakpoint.
        - onEnter: A function which will be called when the viewport is equal to or smaller than the specified width.
        - onLeave: An optional function which will be called when the viewport triggers another registered breakpoint.
    */
    at: function(width, onEnter, onLeave) {
        this._breakpoints[parseInt(width)] = {
            onEnter: onEnter,
            onLeave: onLeave            
        };
    }

};

}(window));