Discovering the screen dimensions or viewport using Javascript in Bootstrap 4

Is there a method to identify the view port/screen size being utilized by Bootstrap 4 using Javascript?

I've been struggling to find a dependable way to determine the current view port after a user resizes the browser. I attempted to use the Bootstrap toolkit, however, it doesn't appear to work properly with Bootstrap 4.

Does anyone have knowledge of an alternative approach?

Answer №1

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

Answer №2

What is the reason behind your decision to download the Bootstrap toolkit?

Here is my tried and tested method that I have been using for years:

1) Within my HTML, I make sure to include the following code just before the closing </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) Additionally, I implement a Javascript function similar to the one below:

function viewSize() {
    return $('#sizer').find('div:visible').data('size');
}

Answer №3

It seems that adjusting the Bootstrap toolkit to be compatible with Bootstrap 4 is quite simple. Just follow these instructions:

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

        // 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>')
        },
    

    with this code:

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

After making these changes, you can utilize the toolkit as usual to detect the screen size:

// Enclose your code in an IIFE
(function($, viewport){
    $(document).ready(function() {

        // Only runs on XS breakpoint
        if(viewport.is('xs')) {
            // ...
        }

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

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

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

Answer №4

Big shoutout to Ander for pointing me in the right direction! I made a little tweak to the code and replaced the bootstrap-3-section with the following:

// Updated 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>')
}

Answer №5

After extensive testing, I have found a solution that works perfectly with Bootstrap 4.2.x:

// Bootstrap 4
responsiveClasses: { 
    '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>') 
}

Answer №6

Expanding on the response provided by @Mr5o1.

To accurately determine the viewport size based on the specified bootstrap guidelines while accounting for a 0.02px difference to address compatibility concerns across various browsers. https://getbootstrap.com/docs/5.2/layout/breakpoints/#max-width

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

    // xs - size below or equal to 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'
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding Gridster to a WordPress theme

I am having an issue with implementing Gridster into my WordPress plugin. Despite correctly loading the necessary files from the folder, it does not seem to work. function add_my_stylesheet() { wp_enqueue_style( 'myCSS', plugins_url( ' ...

Ways to address the issue of "$ is not a function"

Whenever I attempt to upload an image, this error message pops up: $ is not a function The source of the error can be found here: $(document).height(); ...

How can I remove a row from a JavaScript array based on the value of the first item in the row?

Creating an array in JavaScript can be done like this: var myArray = new Array(); myArray.push({ url: urlValue, filename: fileNameValue }); As time goes on, the array will accumulate various items. If you need to delete a specific row based on the urlVal ...

Angularjs drop-down menu changes images with animation

<body ng-controller="myCtrl"> <input type="checkbox" ng-model="loaded"/> <select ng-model="list"> <option ng-repeat="option in data.availableOptions" value="{{option.name}}">{{option.id}}</option> </select> {{list}} &l ...

What is the best way to enclose a bootstrap row within a clickable link generated by the twitch.tv API?

Recently, I completed a JSON/JavaScript project for Free Code Camp that retrieves streamer information like their logo, current status, and display name. My goal is to enclose entire Bootstrap 3 rows in hyperlinks linked to the streamers' pages, elim ...

fluctuating random percentage in JavaScript/jQuery

I am currently faced with the challenge of selecting a random number based on a given percentage ranging from 0 to 5. 0 - 25% (25/100) 1 - 25% (25/100) 2 - 20% (20/100) 3 - 15% (15/100) 4 - 10% (10/100) 5 - 5% (5/100) However, there are instances where ...

Leverage the power of combining Bootstrap and Material-UI in a single project for enhanced

What are the potential effects on my website or web application if I combine both Bootstrap and Material-UI in a project? Thank you. ...

Security Error when using the JavaScript map function in FireFox

My current dilemma involves using a JavaScript code to extract the above-the-fold CSS from my websites. Surprisingly, it functions flawlessly on Google Chrome. However, when I attempt to execute it on Firefox, an infamous 'SecurityError' occurs: ...

Improving Performance When Handling Multiple Events with Socket.io

Exploring socket.io event handling. Which is the more effective approach: socket.on('message', function (message) { if(message.message1) { // perform action } else if (message.message2) { // take alternative action } else ...

My React application is being loaded by Express regardless of the route I access. What could be causing this issue?

I'm struggling to access the json data located at /species because express always seems to load the react app regardless of the route I use. Can someone help me identify the issue? Here is an excerpt from my server.js file: const app = require(' ...

import a function from jQuery that has been defined in an external JavaScript file

Whenever I attempt to execute this action, I encounter an error stating that the function is undefined $(function () { function Example(){ Example1(); } Example1(); }); external.js $(function () { function Example1(){ alert("Hello"); } }); ...

Clicking on a marker in Google Maps will display the address

I have a map that contains several markers, each designated by their latitude and longitude coordinates. I would like to be able to see the address associated with each marker when I click on it. However, I am currently experiencing an issue where nothing ...

Combining two sets of elements in Java to form a Json using Jackson

Is there a way to combine two List of objects retrieved from the database into a single object in order to serialize with Jackson and deserialize in the view? ObjectMapper mapper = new ObjectMapper(); jsonTutorias = mapper.writeValueAsString(tuto ...

Discovering the method for accessing a variable within jQuery from a regular JavaScript function

As someone new to jQuery, I am currently facing a challenge with accessing a variable defined inside a jQuery block from a regular function. Despite my attempts, I have been unsuccessful in accessing it. Can anyone guide me on how to do this? <script l ...

Iterate through an HTML table and transfer matching items along with their corresponding calculated amounts to a separate table

<html> <body> <div> <table border="1" id="topTable"> <thead> <th>Item</th> <th>Sold</th> </thead> <tbody id="topTableBody"> <tr> ...

Unable to fetch the identification number from the database

I'm encountering an issue with retrieving the ID from my database: https://i.sstatic.net/oSAi8.jpg Here is a snapshot of my database: https://i.sstatic.net/j5PpZ.jpg Below is my event controller class: <?php namespace App\Http\Contro ...

Creating an Extjs model for a complex nested JSON structure

Take a look at this JSON structure { "id": 123, "name": "Ed", "orders": [ { "id": 50, "total": 100, "order_items": [ { "id": 20 ...

Searching for and replacing text that spans across multiple nodes in HTML can be accomplished using C# programming language

Here is the HTML code to consider. The term 'response' was modified to 'reason', by removing 'sp' (<del> tag) and adding 'as' (<ins> tag), while also removing 'se' (<del> tag). <div &g ...

Node-zookeeper-client executes the callback for getData method only one time

I have been using node-zookeeper-client in my Node.js server. Everything works smoothly when I watch a znode data with the getData method for the first time. However, I encounter an issue when updating the node (using the ZK-Web user interface) - the wat ...

How can I pass an object into EJS templates from views in Express 3.x?

Currently, I am utilizing ejs templates in combination with node.js and express 3.x. Is there a way to display the data object that is passed into the view? Can it be achieved similar to this example in index.ejs: <%= dump(session) %> ...