Is there a way to detect the view port/screen size used by Bootstrap 4 with Javascript?
I couldn't find a reliable approach to detect the current view port when a user resizes the browser. I have tried the Bootstrap toolkit but it doesn't seem to be compatible with Bootstrap 4.
Does somebody know another approach?
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)
}
Why do you feel the need to donwload the Bootstrap toolkit?
I've been using this approach for years:
1) In HTML I include just before the </body>
tag:
<div id="sizer">
<div class="d-block d-sm-none d-md-none d-lg-none d-xl-none" data-size="xs"></div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none" data-size="sm"></div>
<div class="d-none d-sm-none d-md-block d-lg-none d-xl-none" data-size="md"></div>
<div class="d-none d-sm-none d-md-none d-lg-block d-xl-none" data-size="lg"></div>
<div class="d-none d-sm-none d-md-none d-lg-none d-xl-block" data-size="xl"></div>
</div>
2) And I use a Javascript function like this:
function viewSize() {
return $('#sizer').find('div:visible').data('size');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With