Mobile Exclusive Bootstrap 5 Collapse Feature

Trying to implement the default collapse feature in Bootstrap 5x specifically for mobile devices. Despite setting up a CSS media query as per my research, the .collapse function doesn't seem to work as intended?

The goal is to have the collapsed DIV item visible only on Mobile and fully displayed on devices wider than 768px. However, currently, it remains collapsed across all devices.

<style>

@media screen and (min-width: 768px){
  .collapse {
      display: block;
      height: auto !important;
      visibility: visible;
    }
    .collapsing{
      position: relative;
      height: unset !important;
      overflow: hidden;
    }
}

</style> 




<p>
  <a class="btn btn-primary" data-bs-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
    EXAMPLE
  </a>
</p>
<div class="collapse" id="collapseExample">
  <p>
    Some placeholder content for the collapse component.
  </p>
</div>


Any insights or suggestions on what might be missing?

Answer №1

Substituting

.collapse

By using

.collapse:not(.show)

Solved the problem with the appearance

Answer №2

If you want to hide content on mobile devices initially, you can utilize the mediaQueryList object along with window.matchMedia. This allows you to dynamically set and remove the attribute data-bs-toggle for collapsible elements.

Please Note: When running this snippet, it may appear collapsed due to how the iframe is treated as a window when evaluating media queries. For the best view, try checking the result in fullscreen mode.

const mql = window.matchMedia("(max-width: 767px)");

        const element = document.querySelector('#mobileOnlyCollapse'),
                trigger = document.querySelector('.mobile-only-collapse-trigger');

        let collapseInstance;
        function screenTest(e) {
            if (e.matches) {
                /* the viewport is 767 pixels wide or less */
                trigger.setAttribute('data-bs-toggle','collapse');
                collapseInstance =  new bootstrap.Collapse(element, {})
            } else {
                /* the viewport is more than 767 pixels wide */
                trigger.removeAttribute('data-bs-toggle');
                element.classList.add('show');
            }
        }
        
        // use addEventListener change for mediaQueryList object
        mql.addEventListener("change", screenTest);
        
        //default call with mql object to run on window load
        screenTest(mql);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d0f0202191e191f0c1d2d58435d435f">[email protected]</a>/dist/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4b7bba6b194e6faedfae6">[email protected]</a>/dist/umd/popper.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b6964647f787f796a7b4b3e253b2539">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>


<div>
                        <a role="button" class="btn btn-primary mobile-only-collapse-trigger" data-bs-toggle="collapse" href="#mobileOnlyCollapse" 
                        aria-expanded="false" aria-controls="mobileOnlyCollapse">
                            Trigger button for mobile collapse
                            
                        </a>
                        <div class="card collapse"  id="mobileOnlyCollapse">
                          <div class="card-body" >
                                <span>This content should be collapsed in mobile only but shown all the time in desktop</span>
                                
                            </div>
                            </div>
                    </div>

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

Update the JavaScript to modify the styling based on the specific value of the

Is there a way to apply specific style properties to images only if they already have another property? I've managed to achieve this with the following code snippet: if ($('#content p img').css('float') == 'right') $ ...

Adjustable table region in PHP

I need help with displaying multiple results in a dynamically created table within my program. Even though I want to show around 25 records, the program cuts off after the 5th record, leaving empty space. The issue seems to be that the area does not expand ...

Incorporate functionality into a button using jQuery

I am working on a table that displays data in different levels (Parent, Child, Grandson). When I click on the parent row, it expands to show new rows related to the child level. Similarly, clicking on a child row reveals a third level known as the grandson ...

Design HTML dropdown menu

I have a sleek menu design with rounded buttons, and I am looking to extend the same style to the dropdown list. I have experimented with various approaches but there are two specific issues that I need assistance with: 1. Achieving rounded corners simil ...

What is the reason for the Client Height value not affecting other elements?

I'm trying to set the spacing of my sidebar from the top equal to the height of the header. However, when I use clientHeight in JavaScript to get the height and then try to apply it to other elements using marginTop or top values (with position includ ...

What is the best way to customize the appearance of a table using CSS?

I'm attempting to create a table through RAILS that is automatically generated in the default layout. However, I want to customize its appearance using CSS to achieve the desired look. Specifically speaking, from the attached image, I would like the ...

Ways to adjust the anchor and h1 elements using CSS

I'm working on an HTML document with some markup, <a class="home-link" href="index.html" rel="home"> <h1 class="site-title">John Arellano's Personal Website</h1> </a> While styling the site title, I encountered a problem ...

A guide on retrieving JSON data from an AJAX request using Angular UI Bootstrap

Greetings Friends, I have experience with traditional JavaScript and a little bit of JQuery. Now, for my new JAVA Web Based project, we need to utilize the latest technology to quickly build dynamic web pages. I don't have time to test all the widget/ ...

Modifying button appearance based on state change in AngularJS

I have a button with a grey color and I want to create two different states for it: one that is selected (blue) and another that is in an idle state (grey). Currently, I am working on Angularjs but I am fairly new to this platform. Could you kindly provid ...

What is the best way to include the bootstrap js file in a Next.js 13 project using the new "app directory"?

I recently started using the new app directory in next js 13 and encountered an issue with Bootstrap dropdown. While the UI works fine, the JavaScript features of Bootstrap do not seem to be working properly. I attempted to import the JS file in layout.tsx ...

Is there a way to reverse the animation playback in Angular?

I am working on an animation that involves a box fading from its original color to yellow. However, I would like to achieve the opposite effect: when the page loads, I want the box to start off as yellow and then fade back to its original color. The challe ...

Embellishing Bootstrap with a splash of color class

After exploring Bootstrap, I've noticed the limited number of "color classes" available (primary, success, danger etc.). Is there a simple way to add more classes similar to those? For instance, the "primary" class can be used across various elements ...

Express application is experiencing difficulty displaying the modal

After creating a webpage in HTML with a modal that pops up on button click using jQuery and Bootstrap, everything works perfectly when the files are on my desktop (css, js, fonts, index.html). However, when I transfer the page into my Express application ...

What are the reasons behind the issues encountered when enabling "Optimization" feature in Angular that affect the proper rendering of PrimeNg elements?

Angular Version : 9.x Primeng Version : 9.x We've encountered an issue with PrimeNg elements not rendering correctly in our dev/prod environments, although they work fine in the local environment. After some investigation, we found that the culprit ...

Top method for centering a flexible SVG vertically once the page width becomes too narrow

Currently, I have two SVG images displayed side by side on a webpage. One SVG needs to maintain a fixed size while the other should scale as needed, and I have achieved this functionality. However, I am facing an issue where I want the two SVGs to align v ...

Add a circular transition effect to Font Awesome icons

Check out my code snippet on JSFIDDLE: https://jsfiddle.net/8f3vLh0a/14/ I am using font awesome icons and I would like to add a circling effect on hover similar to this demo: http://tympanus.net/Tutorials/ResponsiveRetinaReadyMenu/ How can I implement t ...

What are some tips for keeping design proportions consistent on mobile apps?

Hey there, I have a question that may seem basic to some, but as a newbie in coding, I appreciate your patience. I've been working on an Ionic app and I'm struggling with maintaining CSS proportions of HTML elements. For instance, here's th ...

The content of InnerHtml does not appear on the screen

I am currently building a web project using HTML and Bootstrap, however, I am facing an issue where my content is not showing up in the browser. Below is the code snippet that I am working with: let str = "" for (let item of r.articles) { s ...

Can a hyperlink open multiple links at the same time when hovered over?

Can two links be opened in the same hyperlink when hovered over? ...

The width of table columns is altered upon the second rendering in JQuery DataTables

Is there a way to prevent JQuery DataTables cells from extending width after adding hyperlink to cell? I am facing an issue where I have two tables on the same page. The first table column has a link which populates the second table. It works fine when th ...