which is the fastest and easy way to fire when bootstrap-responsive.css media queries go in action?
go in action = when you resize window to mobile width and site is changed to responsive mobile
hope question is clear
which is the fastest and easy way to fire when bootstrap-responsive.css media queries go in action?
go in action = when you resize window to mobile width and site is changed to responsive mobile
hope question is clear
Using jquery you can find the size of current window and then accordingly do your stuff.
$(window).resize(function() {
if ($(this).width() >= 1280) {
//do something
}
else if ($(this).width() < 1280 && $(this).width()>= 980) {
//do something
}
...
});
CSS:: Twitter-Bootsrap-layouts
/* Large desktop */
@media (min-width: 1200px) { ... }
/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }
/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }
/* Landscape phones and down */
@media (max-width: 480px) { ... }
I came up with an approach that uses window resize event, but relying on Twitter Bootstrap's media queries without hard coding their breakpoints:
<span id="mq-detector">
<span class="visible-xs"></span>
<span class="visible-sm"></span>
<span class="visible-md"></span>
<span class="visible-lg"></span>
</span>
#mq-detector {
visibility: hidden;
}
var currMqIdx = undefined;
var mqDetector = $("#mq-detector");
var mqSelectors = [
mqDetector.find(".visible-xs"),
mqDetector.find(".visible-sm"),
mqDetector.find(".visible-md"),
mqDetector.find(".visible-lg")
];
var checkForResize = function() {
for (var i = 0; i <= mqSelectors.length; i++) {
if (mqSelectors[i].is(":visible")) {
if (currMqIdx != i) {
currMqIdx = i;
console.log(mqSelectors[i].attr("class"));
}
break;
}
}
};
$(window).on('resize', checkForResize);
checkForResize();
One issue with the other answers is the change event is triggered EVERY resize. This can be very costly if your javascript is doing something significant.
The code below calls your update function only one time, when a threshold is crossed.
To test, grab your window size handle, and drag resize it quickly to see if the browser chokes.
<script>
// Global state variable
var winSize = '';
window.onresize = function () {
var newWinSize = 'xs'; // default value, check for actual size
if ($(this).width() >= 1200) {
newWinSize = 'lg';
} else if ($(this).width() >= 992) {
newWinSize = 'md';
} else if ($(this).width() >= 768) {
newWinSize = 'sm';
}
if( newWinSize != winSize ) {
doSomethingOnSizeChange();
winSize = newWinSize;
}
};
</script>
This works for me in combination with Bootstrap 3:
<div id="media-width-detection-element"></div>
<style type="text/css">
#media-width-detection-element {
display: none;
width: 0px;
}
@media (min-width: 768px) {
#media-width-detection-element {
width: 768px;
}
}
@media (min-width: 992px) {
#media-width-detection-element {
width: 992px;
}
}
@media (min-width: 1200px) {
#media-width-detection-element {
width: 1200px;
}
}
</style>
<script type="text/javascript">
//<![CDATA[
function xs() {
return $("#media-width-detection-element").css("width") === "0px";
}
function sm() {
return $("#media-width-detection-element").css("width") === "768px";
}
function md() {
return $("#media-width-detection-element").css("width") === "992px";
}
function lg() {
return $("#media-width-detection-element").css("width") === "1200px";
}
//]]>
</script>
The hidden DIV change width depending on the actual CSS min-width settings in use. Then my javascript simple check the current with of the DIV.
Excellent Tip, @falsarella!
For those who like this sort of thing to not affect their actual markup the following works:
$(function(){
...
var mqClasses = ["visible-xs", "visible-sm", "visible-md", "visible-lg"];
var mq = $("<span id='mqDetector' style='visibility:hidden'></span>").appendTo($("body"));
$.each(mqClasses, function(idx, val) {
mq.append("<span class='" + val + "'></span>");
});
function checkMQ() {
var visible = mq.find(":visible").get(0).className;
return visible.slice(-2);
};
function checkResize(){
switch(checkMQ){
case 'xs' : ...; break;
case 'sm' : ...; break;
...
}
}
$(window).on('resize', checkResize);
checkResize(); //do it once when page loads.
Based on @falsarella's solution, the js part can be simplified to:
var currMqIdx = undefined;
var checkForResize = function() {
currMqIdx = $('#mq-detector span').index($('#mq-detector span:visible'));
};
$(window).on('resize', checkForResize);
checkForResize();
currMqIdx
would be an int value, from 0 to 3. The bigger currMqIdx
is, the wider the media is.
this code add body tag ld, md, sd or xd class
$(function(){
var device_width_detect = '';
function device_detec(){
if ($(this).width() >= 1280) {
device_width_detect = 'ld';
}else if ($(this).width() < 1280 && $(this).width()>= 992) {
device_width_detect = 'md';
}else if ($(this).width() < 992 && $(this).width()>= 768) {
device_width_detect = 'sd';
}else if ($(this).width() < 768) {
device_width_detect = 'xd';
}
$('body').removeClass( "ld md sd xd" ).addClass( device_width_detect );
}
device_detec();
$(window).on('resize', device_detec);
});
I have prepered a super lightweight library to deal with events fired when window width and Bootstrap breakpoint is changed - responsive-breakpoint-tester
var viewport = new ResponsiveTester();
$('body').on('in.screen.xs', function(event, devices) {
// Code executed when viewport is was changed to xs
});
$('body').on('out.screen.xs', function(event, devices) {
// Code executed when viewport is no longer xs
});
Other features like current breakpoint check are also included:
if (viewport.is('xs')) {
// Executed only on xs breakpoint
}
if (viewport.is('!=xs')) {
// Executed on all breakpoints that are not equal xs (sm, md, lg)
}
if (viewport.is('<md')) {
// Executed on breakpoints that are smaller than md (xs, sm)
}
if (viewport.is('<=md')) {
// Executed on breakpoints that are smaller or equal to md (xs, sm, md)
}
if (viewport.is('>md')) {
// Executed on breakpoints that are larger than md (lg)
}
Bootstrap 4 and Foundation configuraions are supported, more info on GitHub Repository
You can use matchMedia
and a wrapper library enquire.js
which registers media queries and emits events when they are matched/unmatched.
Let's use these Bootstrap CSS media queries as an example taken from the docs.
/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */
/* Small devices (tablets, 768px and up) */
@media (min-width: @screen-sm-min) { ... }
/* Medium devices (desktops, 992px and up) */
@media (min-width: @screen-md-min) { ... }
/* Large devices (large desktops, 1200px and up) */
@media (min-width: @screen-lg-min) { ... }
To see when each of these rules get applied, use enquire.js
to register the media queries and supply appropriate match
and unmatch
functions, as below:
let rules = [
'(max-width: 768px)', // extra small devices, default
'(min-width: 768px)', // small devices
'(min-width: 992px)', // medium devices
'(min-width: 1200px)' // large devices
];
for (let rule of rules) {
enquire.register(rule, {
match: function() {
console.log(rule + ' matched');
},
unmatch: function() {
console.log(rule + ' unmatched');
}
});
}
enquire.js
uses matchMedia
which supports only the modern browsers, no IE9 for example. So polyfill will be needed for legacy browsers to make this work.
Simpler
$(window).on('resize', function () {
if ($('<div class="visible-lg">').css('display')=='block') {
// Do something for lg
}
// ...
});
I used this to only stick the navbar at https://ducttapedanyol.com in bootstrap on large screens:
if ($(this).width() >= 979) { // Detect screen size
$(document).ready(function () {
var menu = $('.menu');
var origOffsetY = menu.offset().top;
function scroll() {
if ($(window).scrollTop() >= origOffsetY) {
$('.menu').addClass('sticky');
$('.fix').addClass('fix-tall');
} else {
$('.menu').removeClass('sticky');
$('.fix').removeClass('fix-tall');
}
}
document.onscroll = scroll;
});
}
I have revised codes in this link to Bootsrap 4 not alpha or beta. Codes as below;
/* **********************************************************
Detect bootrap 4 media query type
https://getbootstrap.com/docs/4.0/utilities/display/
********************************************************** */
$("body").append("<div style='visibilty:hidden' class='viewport-check'><span class='d-block d-sm-none'>xs</span><span class='d-none d-sm-block d-md-none'>sm</span><span class='d-none d-md-block d-lg-none'>md</span><span class='d-none d-lg-block d-xl-none'>lg</span><span class='d-none d-xl-block'>xl</span></div>");
var Bootstrap4MediaQuery = "";
//> Checks if the span is set to display block via CSS
function FnDetectMediaQuery(_QsTarget) {
var _QsTarget = $(_QsTarget).css('display') == 'block';
return _QsTarget;
}
if(FnDetectMediaQuery('.viewport-check .d-block') == true)
{
Bootstrap4MediaQuery = "xs";
}
else if(FnDetectMediaQuery('.viewport-check .d-sm-block') == true)
{
Bootstrap4MediaQuery = "sm";
}
else if(FnDetectMediaQuery('.viewport-check .d-md-block') == true)
{
Bootstrap4MediaQuery = "md";
}
else if(FnDetectMediaQuery('.viewport-check .d-lg-block') == true)
{
Bootstrap4MediaQuery = "lg";
}
else if(FnDetectMediaQuery('.viewport-check .d-xl-block') == true)
{
Bootstrap4MediaQuery = "xl";
}
else
{
Bootstrap4MediaQuery = "";
}
console.log("Bootstrap4MediaQuery: " + Bootstrap4MediaQuery);
here is my solution for bootstrap 4, based on @falsarella idea
*note: use "full page" option below for test this snippet, otherwise it will return wrong screen type, based on snippet iframe size
/**
* @returns STRING current screen type like: xs, sm, md, lg or xl
*/
function getScreenType() {
!function initHelpers() {
if ($('div.mq-detector').length !== 0) return;
$('body').append(_mqDetector());
// helpers
function _mqDetector() {
return `
<div class="mq-detector invisible">
<div
class="d-block d-sm-none"
data-type="xs"></div>
<div
class="d-none d-sm-block d-md-none"
data-type="sm"></div>
<div
class="d-none d-md-block d-lg-none"
data-type="md"></div>
<div
class="d-none d-lg-block d-xl-none"
data-type="lg"></div>
<div
class="d-none d-xl-block"
data-type="xl"></div>
</div>
`;
}
}();
// @then
return $('div.mq-detector').children().filter(':visible').data('type');
}
console.log(getScreenType())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">