Responsive Event Delegation

by Gustavo Carvalho

HTML

<div id="my-component">

    <div class="inner">

        <div class="call-to-action">
            Do Stuff...
        </div>

    </div>

</div>

CSS

body:after {
    position: absolute;
    bottom: 0;
    right:0;
}
        
.call-to-action {
    margin: 3em;
    padding: 1em;
    background: yellow;
    border-radius: 5px;
    cursor: pointer;
    border: 1px solid #ccc;
}

@media screen and (min-width: 0px) and (max-width: 320px) {
    body:after {
        content: 'less than 320px';
    }
}

@media screen and (min-width: 321px) and (max-width: 768px) {
    body:after {
        content: 'more than 320';
    }        
}

JavaScript

var cache = [];
/**
 * Step 1
 */
var breakpoints = {

    bp1: 'screen and (min-width: 0px) and (max-width: 320px)',

    bp2: 'screen and (min-width: 321px)'

    //etc...

};

/**
 * Step 2
 */
for ( var name in breakpoints ){

    // need to scope variables in a for loop
    !function(breakName, query){

        // the callback
        function cb(data){

            // add class name associated to current breakpoint match
            $( '#my-component .inner' ).toggleClass( breakName, data.matches );

            // potentially do other stuff if you want...

        }

        // run the callback on current viewport
        cb({
            media: query,
            matches: matchMedia(query).matches
        });

        // subscribe to breakpoint changes
        var m = matchMedia(query);
        m.addListener( cb );
        cache.push(m); //fix for firefox, store a reference

    }(name, breakpoints[name]);
}

/**
 * Step 3
 */
$( '#my-component' )
.on({

        //click events
        click: function(e){ 
            $(this).html('You clicked');
        }

    },

    //query string to match .call-to-action but only in first breakpoint
    '.bp1 .call-to-action'
)
.on({

        //mouse events
        mouseenter: function(e){
            $(this).html('You mouseentered');
        },

        mouseleave: function(e){ 
            $(this).html('You mouse...left...');
        }

    },

    //query string to match .call-to-action on all EXCEPT first breakpoint
    '.bp2 .call-to-action'
);