How To Detect Bootstrap Responsive Breakpoints In Javascript

 

<section id="content-1-3" class="content-block content-1-3">
	<div class="container">
		<div class="row">
		    <div class="appc-helper device-xs visible-xs" data-device="xs">XS</div>
            <div class="appc-helper device-sm visible-sm" data-device="sm">SM</div>
            <div class="appc-helper device-md visible-md" data-device="md">MD</div>
            <div class="appc-helper device-lg visible-lg" data-device="lg">LG</div>
            <h1>Device Mode (js):</h1>
            <div class="mode"></div>
		</div><!-- /.row -->
	</div><!-- /.container -->
</section>

 

.appc-helper {
    float: left;
    position: fixed;
    top: -10000px;
}

 

// @see: http://stackoverflow.com/questions/18575582/how-to-detect-responsive-breakpoints-of-twitter-bootstrap-3-using-javascript

// Detects which UI element is visible
function getBreakPoint() {
   var device = $('[class*="device-"]').filter(':visible').attr('data-device');
    return device;
}

// check for changes
var waitForFinalEvent = function() {
    // Create a private scope to set, clear, and check for timeout.
    // This will prevent too many timeout intervals from being set.
    var b = {};
    return function(func, intervalTime, timeStamp) {
        // create a key name using timeStamp, if provided
        timeStamp || (timeStamp = "unknown");
        // if key is set in private scope, clear interval
        b[timeStamp] && clearTimeout(b[timeStamp]);
        // set timeout for the timeStamp key
        b[timeStamp] = setTimeout(func, intervalTime)
    }
}();

// initial, unique interval name.
var fullDateString = new Date();

// how often to check for changes in the layout
var checkEvery = 250;

$(window).resize(function () {
    waitForFinalEvent(function(){
        var mode = getBreakPoint();
        setMode(mode);
    }, checkEvery, fullDateString.getTime())
});

// not in use but handy
function isBreakpoint( alias ) {
    return $('.device-' + alias).is(':visible');
}

// set changes in the UI
function setMode(mode) {
    var $mode = $('.mode');
        $mode.html(mode);
}

var mode = getBreakPoint();
setMode(mode);

 

Leave a Reply

Your email address will not be published. Required fields are marked *