JSFiddle - React, Tailwind, and code Playground
by timmah
HTML
<span id="mobile-test"></span>
CSS
#mobile-test {
/*display: none;*/
display: block;
width:10px;
height: 10px;
background-color:red;
content: 'mq-small';
}
@media and (min-width: 480px) {
#mobile-test {
background-color:blue;
content: 'mq-medium';
}
}
@media and (min-width: 768px) {
#mobile-test {
background-color:green;
content: 'mq-large';
}
}
JavaScript
// Allow resizing to be assessed only after a delay, to avoid constant firing on resize.
var resize;
window.onresize = function() {
clearTimeout(resize);
// Call 'onResize' function after a set delay
resize = setTimeout(onResize, 100);
};
// Collect the value of the 'contnet' property as a string, stripping the quotation marks
function onResize() {
console.log($('#mobile-test').css('content').replace(/"/g, ''));
return $('#mobile-test').css('content').replace(/"/g, '');
}
// Finally, use the function to detect the current media query, irrespective of it's breakpoint value
$(window).on('resize load', function() {
if (onResize() === 'mq-small') {
// Do stuff for small screens etc
console.log('mq-small');
} else if (onResize() === 'mq-medium') {
// Do stuff for small screens etc
console.log('mq-medium');
} else if (onResize() === 'mq-large') {
// Do stuff for small screens etc
console.log('mq-large');
}
});