Tips for changing the visibility of content by combining various Bootstrap 4 display classes

Struggling to figure out a seamless way to toggle the display of a side navigation bar while incorporating multiple Bootstrap 4 display classes due to their heavy use of !important.

For instance, consider this div using the display classes that I need to toggle the display on.

<div class="module-name d-none d-lg-block sb-collapsable">
     {{module_name}}
</div>>

I'm finding it quite challenging to toggle this display because both the d-none and d-lg-block classes utilize display: none/block !important. The sb-collapsable class is included for identifying elements to hide in jQuery. Any advice would be highly appreciated. I've tested various solutions and searched extensively for similar issues but haven't had any luck.

Edit: It's important to note that not all divs with the sb-collapsable class have identical classes assigned. Here's another example where I need to toggle the visibility without knowing the initial display state before JavaScript execution.

<a class="d-block d-lg-none brand bg-dark sb-collapsable" href="#">XXX</a>

Answer №1

I encountered a similar issue and created a solution called bs4_display.js to address it (you can find the complete code on this gist). This script, when hiding elements, replaces any d-*-block classes with placeholder ones like dummy-*-block. If you later decide to show that element, it reverts back to the original classes. You can see a fully functional example on jsbin. The API includes:

bs4Display.show([HTMLelement]);
bs4Display.hide([HTMLelement]);
bs4Display.reset([HTMLelement]);

(function(window){
  'use strict';

  // wrapper
  function bs4Display() {
    var _bs4Display = {};

    _bs4Display.DUMMY_PREFIX = 'dummy'

    // private methods
    _bs4Display._build_block_classes = function () {
      if (_bs4Display._displayBlocks) {
        return _bs4Display._displayBlocks;
      }
      var prefix = _bs4Display.DUMMY_PREFIX;
      _bs4Display._blockArray = [
        ['d-block',    prefix + '-block'],
        ['d-sm-block', prefix + '-sm-block'],
        ['d-md-block', prefix + '-md-block'],
        ['d-lg-block', prefix + '-lg-block'],
        ['d-xl-block', prefix + '-xl-block']
      ];
      _bs4Display._noneArray = [
        [prefix + '-none',    'd-none'],
        [prefix + '-sm-none', 'd-sm-none'],
        [prefix + '-md-none', 'd-md-none'],
        [prefix + '-lg-none', 'd-lg-none'],
        [prefix + '-xl-none', 'd-xl-none']
      ];
      _bs4Display._displayBlocks = _bs4Display._blockArray.concat(_bs4Display._noneArray);
      return _bs4Display._displayBlocks;
    }

    if (typeof(document.querySelector('body').classList.replace) !== 'undefined') {
      // native replace
      _bs4Display._replace = function (el, oldClass, newClass) {
        return el.classList.replace(oldClass, newClass);
      }
    } else {
      // polyfill, since support is not great:
      // https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Browser_compatibility
      _bs4Display._replace = function (el, oldClass, newClass) {
        if (el.classList.contains(oldClass)) {
          el.classList.remove(oldClass);
          el.classList.add(newClass);
        }
      }
    }

    // public methods
    /**
     * Hides a HTML element with BootStrap 4 markup
     * @param {Element|[Element]} els - HTML element(s) to hide.
     */
    _bs4Display.hide = function (els) {
      if (!els) { return; }  // nothing to hide
      if (!(els instanceof Array)) { els = [els]; }
      var dBlocks = _bs4Display._build_block_classes();
      for (var k = 0; k < els.length; k++) {
        for (var i = 0; i < dBlocks.length; i++) {
          _bs4Display._replace(els[k], dBlocks[i][0], dBlocks[i][1]);
        }
        els[k].style.display = 'none';
      }
    }

    /**
     * Shows a HTML element with BootStrap 4 markup
     * @param {Element|[Element]} els - HTML element(s) to show.
     */
    _bs4Display.show = function (els) {
      if (!els) { return; }  // nothing to show
      if (!(els instanceof Array)) { els = [els]; }
      var dBlocks = _bs4Display._build_block_classes();
      for (var k = 0; k < els.length; k++) {
        for (var i = 0; i < dBlocks.length; i++) {
          _bs4Display._replace(els[k], dBlocks[i][1], dBlocks[i][0]);
        }
        els[k].style.display = '';
      }
    }

    /**
     * Restores the HTML elements original display classes
     * @param {Element|[Element]} els - HTML element(s) to reset.
     */
    _bs4Display.reset = function (els) {
      if (!els) { return; }  // nothing to show
      if (!(els instanceof Array)) { els = [els]; }
      _bs4Display._build_block_classes();
      for (var k = 0; k < els.length; k++) {
        for (var i = 0; i < _bs4Display._blockArray.length; i++) {
          _bs4Display._replace(els[k], _bs4Display._blockArray[i][1], _bs4Display._blockArray[i][0]);
          _bs4Display._replace(els[k], _bs4Display._noneArray[i][0], _bs4Display._noneArray[i][1]);
        }
        els[k].style.display = '';
      }
    }

    return _bs4Display;
  }

  if(typeof(window.bs4Display) === 'undefined') {
    window.bs4Display = bs4Display();
  }
})(window);

// optional, change prefix before first call
// window.bs4Display.DUMMY_PREFIX = 'bs4-display'
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>BootStrap 4 Show/Hide</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
  <p>
    <button onclick="bs4Display.show(document.getElementById('none'));" type="button" class="btn btn-primary">Show d-none</button>
    <button onclick="bs4Display.hide(document.getElementById('none'));" type="button" class="btn btn-secondary">Hide d-none</button>
    <button onclick="bs4Display.reset(document.getElementById('none'));" type="button" class="btn btn-info">Reset d-none</button>
  </p>
  <p>
    <button onclick="bs4Display.show(document.getElementById('block'));" type="button" class="btn btn-success">Show d-block</button>
    <button onclick="bs4Display.hide(document.getElementById('block'));" type="button" class="btn btn-danger">Hide d-block</button>
    <button onclick="bs4Display.reset(document.getElementById('block'));" type="button" class="btn btn-info">Reset d-block</button>
  </p>
  
  <div class="container">
  <div id="none" class="d-none p-2 bg-primary text-white">d-none</div>
  <div id="block" class="d-block p-2 bg-dark text-white">d-block</div>
    
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>

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

Why is it displaying undefined even though there is data stored in Firebase?

I am experiencing an issue where the datatable row is displaying "undefined" instead of the data from my Firebase database. Even when I tried inserting random data into the HTML file for the datatable, it still shows undefined. Here is a link to My Datata ...

Updating the state in React can be achieved by using the `

Upon obtaining a list of search results, each result is equipped with an onclick function. My goal is to exhibit the user-selected results on the screen by adding them to an array upon click: let selectedData = [] function addFunc(resultdata){ consol ...

Troubleshooting JSONP Implementation with JQuery: Scope versus Async Problems

I've been trying to call a JSONP service using the $.ajax function: $.ajax({ url: jsonpURI, dataType: "jsonp", jsonpCallback: callback, success: function () { console.log("Success"); }, error: function (err) { ...

Reposition the jQuery tooltip arrow

I need help adjusting the position of the arrow to the left near the text box. Can anyone assist with this? Here's what I've tried so far: Check out the working example here: http://jsfiddle.net/b8fcg/ HTML: <input id="test" title="We ask ...

An easy guide to using validators to update the border color of form control names in Angular

I'm working on a form control and attempting to change the color when the field is invalid. I've experimented with various methods, but haven't had success so far. Here's what I've tried: <input formControlName="pe ...

Determine the current state of the parent by analyzing the child components' data in ReactJS

I am currently working on implementing a settings page that includes both global settings and child settings in the form of sliders. Here are the scenarios I need to address: 1) When all child settings are turned on, the parent switch state should also b ...

Web Browser Fails to Set Cookie during an Ajax Request

I am facing a perplexing issue. I have an AJAX call that triggers the processing of a login form and generates a cookie upon successful login. However, the web browser is failing to recognize the cookie. Upon troubleshooting, I have narrowed it down to so ...

HTML - maintain centered text positioning while implementing padding on the left side

Here are the HTML and CSS code snippets I am working with: #page { background-color: #000; color: #fff; height: 360px; width: 360px; min-height: 100%; } #viewport { font-size: 20pt; text-align: center; } .taskTitle { height: 13%; fon ...

Add PHP functionality to insert a jQuery array of select2 tags

After browsing numerous threads on various platforms regarding this issue, I have yet to find a solution. Therefore, I am reaching out for help once again. I am currently utilizing the select2 jQuery plugin and aiming to insert tags into an SQL database us ...

Overlapping Bootstrap rows in small screens

I'm currently working on a frontend project using bootstrap 5, specifically utilizing the grid system to ensure responsiveness across different devices. However, I've encountered an issue in my code that I can't quite figure out. The probl ...

fetch information using ajax and jquery

I'm facing an issue with my ajax request on my website. I'm trying to dynamically fetch pages from a database using jquery and ajax. However, I'm not getting any response, and I'm unsure whether the problem lies in my php code or my j ...

Error in Rails 4: Unable to call $(...).previous function - TypeError

I've been attempting to create a link labeled "remove" underneath a text field to use JavaScript to destroy and hide it, but I'm running into an issue where it doesn't work and I'm receiving this error in the console: TypeError: $(...). ...

How can I send an HTML document from a WebApi 2 action using the IHttpActionResult interface?

When it comes to building an html document and returning it in a web api, many resources recommend using HttpResponseMessage. However, I am eager to achieve this using IHttpActionResult instead. Here is my current approach: [ResponseType(typeof(HttpRe ...

Changing the font-family on the dropdown menu provided by Codrops seems to be difficult

Looking for help with the Tympanus Codrops Dropdown Menu - SimpleDropDownEffects. I'm having trouble changing the font-family on my website. I am using Icomoon for the icons, and while that works fine, I can't seem to properly format the text ho ...

The error message "Multiple children error occurs when an empty link in Next.js

Is there a way to successfully implement a <Link /> element without any content inside it in my application? Surprisingly, when I don't provide any content, I encounter the multiple children error, even though the opposite seems to be happening. ...

Can you provide a method for verifying an 'undefined' variable in AJAX queries?

How can we elegantly check if a variable is undefined in JavaScript? $.ajax({ type: method, url: url, success: function (data) { if (form != null || form != undefined){ data = $(form).serialize(); } var json ...

Develop a persistent overlay with HTML and CSS

I've been working on a project (HTML and CSS page) that features a navbar at the top of the page, a main container below the navbar, and a menu on the left side. The menu is initially hidden, but when I move my mouse to the left edge of the window, i ...

The <HTML> element is just a bit too big for the screen

When viewing my webpage on mobile, the video background does not fit the screen properly (it fits in landscape orientation). Here is the video tag I am using: <video autoPlay loop muted playsInline className='absolute w-full h- ...

Eliminate the space between the navigation bar and carousel when using Materialize with Vue.js and Laravel

I am facing an issue with the gap between the navbar and carousel in my materialize design. I have implemented Vue components for each div and Laravel as the backend. Using Sass for CSS preprocessing, I attempted to adjust the margins for the body, navbar, ...

Avoid loading external scripts from third-party sources such as JavaScript libraries, Bing Maps API, and Lighthouse performance tool

Issue: The Bing maps API I incorporated into my assignment is loading unnecessary CSS and scripts, causing a noticeable decrease in my lighthouse scores. Is there a way to prevent third-party code (such as Bing Ads) from loading when fetching the maps for ...