Responsive Elements

by AaronLayton

HTML

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<div class="container">
    <div class="row">
        <div class="col-md-4 col-sm-6">
            
            
            <div class="associated-product" data-responsive="720|350|280"></div> 
            
            
            
        </div>
        <div class="col-md-4 col-sm-6">
            <div class="associated-product responsive-12312412" data-responsive="720|350|280"></div>
        </div>
        <div class="col-md-4 col-sm-12 clearfix">
            <div class="associated-product responsive-123657562" data-responsive="720|350|280"></div>
        </div>
    </div>
</div>

SCSS

.associated-product {
    border:2px solid #f00;
    min-height:100px;
    
    &.responsive-280 {
         border-color:#00f;
    }
    &.responsive-350 {
         border-color:#f0f;
    }
    &.responsive-720 {
         border-color:#000;
    }
}

JavaScript

// http://kumailht.com/responsive-elements/

var allResponsiveItems = $("[data-responsive]"),
    resizeTimeout;

if (allResponsiveItems.length > 0) {
    $(window).load(function(){
        updateResponsive();
    });
}

$(window).on("resize", function(){
    clearTimeout(resizeTimeout);
    
    resizeTimeout = setTimeout(function(){
        updateResponsive();
    }, 500);
});

function updateResponsive(){
    allResponsiveItems.each(function(index,element){
        
        var thisBox = $(this);
            thisBoxWidth = thisBox.width();
        
        // Remove all old classes
        $(element).removePrefixedClasses("responsive-");
        
        var sizes = $(element).data("responsive").split("|");
        
        $.each(sizes, function(index, size){
            
            if (thisBoxWidth > size){
                thisBox.addClass("responsive-" + size);
            }
        });
    });
}













(function ($) {
    $.fn.removePrefixedClasses = function (prefix) {
        var classNames = $(this).attr('class').split(' '),
            className,
            newClassNames = [],
            i;
        //loop class names
        for(i = 0; i < classNames.length; i++) {
            className = classNames[i];
            // if prefix not found at the beggining of class name
            if(className.indexOf(prefix) !== 0) {
                newClassNames.push(className);
                continue;
            }
        }
        // write new list excluding filtered classNames
        $(this).attr('class', newClassNames.join(' '));
    };
}(jQuery));