Ander
Ander

Reputation: 5644

How to detect screen size or view port on Bootstrap 4 with Javascript

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?

Upvotes: 4

Views: 16777

Answers (6)

Mr5o1
Mr5o1

Reputation: 1828

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'
  if (width <= 1400) return 'xl'
  return 'xxl'
}

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)
}

Upvotes: 12

MR_AMDEV
MR_AMDEV

Reputation: 1942

Extending the answer from @Mr5o1.

To get the precise viewport size according to defined bootstrap recommendations. There is 0.02px difference to cover compatibility issues along multiple browsers. https://getbootstrap.com/docs/5.2/layout/breakpoints/#max-width

getViewport () {
    const width = Math.max(
      document.documentElement.clientWidth,
      window.innerWidth || 0
    )

    // xs - size less than or 575.98
    if (width <= 575.98) return 'xs'
    // sm - size between 576 - 767.98
    if (width >= 576 && width <= 767.98) return 'sm'
    // md - size between 768 - 991.98
    if (width >= 768 && width <= 991.98) return 'md'
    // lg - size between 992 - 1199.98
    if (width >= 992 && width <= 1199.98) return 'lg'
    // xl - size between 1200 - 1399.98
    if (width >= 1200 && width <= 1399.98) return 'xl'

    // xxl- size greater than 1399.98
    return 'xxl'
}

Upvotes: 0

Alexandre Paulo
Alexandre Paulo

Reputation: 2455

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');
}

Upvotes: 9

CJ Ratliff
CJ Ratliff

Reputation: 333

None of the other answers we working as of Bootstrap 4.2.x, the following works however:

// Bootstrap 4
bootstrap: { 
    'xs': $('<div class="device-xs d-block d-sm-none">xs</div>'), 
    'sm': $('<div class="device-sm d-none d-sm-block d-md-none">sm</div>'),
    'md': $('<div class="device-md d-none d-md-block d-lg-none">md</div>'),     
    'lg': $('<div class="device-lg d-none d-lg-block d-xl-none">lg</div>'), 
    'xl': $('<div class="device-lg d-none d-xl-block">xl</div>') 
}

Upvotes: 1

simaglei
simaglei

Reputation: 1248

Thank you, Ander, for bringing me on the right track! However I had to replace the bootstrap-3-section by the following:

// Bootstrap 4
bootstrap: {
    'xs': $('<div class="device-xs d-block d-sm-none" ></div>'),
    'sm': $('<div class="device-sm d-none d-sm-block d-md-none"></div>'),
    'md': $('<div class="device-md d-none d-sm-none d-md-block d-lg-none"></div>'),
    'lg': $('<div class="device-lg d-none d-sm-none d-md-none d-lg-block d-xl-none"></div>'),
    'xl': $('<div class="device-lg d-none d-sm-none d-md-none d-lg-none d-xl-block"></div>')
}

Upvotes: 1

Ander
Ander

Reputation: 5644

Looks like we can easily tweak the Bootstrap toolkit to make it compatible with Bootstrap 4, just follow these steps:

  1. Download the Bootstrap toolkit.
  2. Replace the following code:

        // Bootstrap 3
        bootstrap: {
            'xs': $('<div class="device-xs visible-xs visible-xs-block"></div>'),
            'sm': $('<div class="device-sm visible-sm visible-sm-block"></div>'),
            'md': $('<div class="device-md visible-md visible-md-block"></div>'),
            'lg': $('<div class="device-lg visible-lg visible-lg-block"></div>')
        },
    

    by this one:

        // Bootstrap 4
        bootstrap: { 
            'xs': $('<div class="device-xs hidden-sm-up">xs</div>'), 
            'sm': $('<div class="device-sm hidden-xs-down hidden-md-up">sm</div>'),
            'md': $('<div class="device-md hidden-sm-down hidden-lg-up">md</div>'),     
            'lg': $('<div class="device-lg hidden-xl-up hidden-md-down">lg</div>'), 
            'xl': $('<div class="device-lg hidden-lg-down">xl</div>') 
        }
    

Then you can use the toolkit normally to detect the screen size:

// Wrap IIFE around your code
(function($, viewport){
    $(document).ready(function() {

        // Executes only in XS breakpoint
        if(viewport.is('xs')) {
            // ...
        }

        // Executes in SM, MD and LG breakpoints
        if(viewport.is('>=sm')) {
            // ...
        }

        // Executes in XS and SM breakpoints
        if(viewport.is('<md')) {
            // ...
        }

        // Execute code each time window size changes
        $(window).resize(
            viewport.changed(function() {
                if(viewport.is('xs')) {
                    // ...
                }
            })
        );
    });
})(jQuery, ResponsiveBootstrapToolkit);

Upvotes: 1

Related Questions