I'm not really sure why all answers involve inserting an element into the DOM just to check whether it will be displayed? DOM manipulations are expensive, why not just read the viewport width directly?
This S/O Question provides the best way to read the width. Converting that to a bootstrap width is easy enough:
function getViewport () {
// https://stackoverflow.com/a/8876069
const width = Math.max(
document.documentElement.clientWidth,
window.innerWidth || 0
)
if (width <= 576) return 'xs'
if (width <= 768) return 'sm'
if (width <= 992) return 'md'
if (width <= 1200) return 'lg'
return 'xl'
}
If you want some kind of event to fire every time the viewport changes...
$(document).ready(function () {
let viewport = getViewport()
let debounce
$(window).resize(() => {
debounce = setTimeout(() => {
const currentViewport = getViewport()
if (currentViewport !== viewport) {
viewport = currentViewport
$(window).trigger('newViewport', viewport)
}
}, 500)
})
$(window).on('newViewport', (viewport) => {
// do something with viewport
})
// run when page loads
$(window).trigger('newViewport', viewport)
}