It's puzzling why many solutions involve adding an element to the DOM just to check its display. DOM manipulations can be costly, so why not simply access the viewport width directly?
For the most efficient method of obtaining the width, refer to this Stack Overflow post. Converting this value to a Bootstrap width classification is a straightforward process:
function getViewport () {
// Utilizing method from 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'
if (width <= 1400) return 'xl'
return 'xxl'
}
If you're looking to trigger an event whenever 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) => {
// Implement actions based on viewport
})
// Execute upon page load
$(window).trigger('newViewport', viewport)
}