JS call for Bootstrap 5 collapse toggle not functioning as expected

I'm exploring the use of JavaScript to display or hide a collapsible element without toggling between the two states. In other words, I want to prevent the toggle functionality.

According to the information provided in the documentation at https://getbootstrap.com/docs/5.0/components/collapse/#via-javascript, it's suggested that with the following code snippet, toggling between shown and hidden can be achieved:

var myCollapse = document.getElementById('myCollapse')
        var bsCollapse = new bootstrap.Collapse(myCollapse, {
          toggle: true
        })
    

If we change the 'toggle' attribute to false, the behavior stops as expected. However, there is mention of using the 'show' and 'hide' properties within an object passed as the second argument to enable/disable these actions:

var myCollapse = document.getElementById('myCollapse')
        var bsCollapse = new bootstrap.Collapse(myCollapse, {
          toggle: false,
          show: true,
          hide: false
        })
    

But when attempting to utilize these options individually, only the 'toggle' option seems to work. Upon inspecting the Bootstrap JavaScript source code, it appears that the library checks the status of the 'toggle' parameter:

if (_this._config.toggle) {
            _this.toggle();
          }
    

However, there doesn't seem to be a similar check for 'show' and 'hide', indicating that these options may not have any effect when utilized within the bootstrap.Collapse() method.

Do you believe my understanding is accurate, that the 'show' and 'hide' options do not function properly with bootstrap.Collapse()? If not, could you provide guidance on what might be causing this issue?

Answer №1

Toggle is not only a configuration option but also a method called here and described as a method using .toggle()

Show() and hide() are mentioned as methods, not as configuration options.

So, trying to use them as configuration options like this won't have any effect...

var bsCollapse = new bootstrap.Collapse(myCollapse, {
  toggle: false,
  show: true, //not useful
  hide: false //not useful
})

However, making use of show() and hide() will work properly...

bsCollapse.show()

or

bsCollapse.hide()

Check out the demo here

Answer №2

To easily toggle the collapse feature:

new bootstrap.Collapse(myCollapse, {
  toggle: true
});

- Ensure that the toggle option is set to true.

=> Activates the collapsible element when the instance constructor is invoked.

- No need to assign a variable to the collapse instance.

If you wish to show or hide the collapse:

var bsCollapse = new bootstrap.Collapse(myCollapse, {
  toggle: false
})

bsCollapse.show();

or

bsCollapse.hide();

- Set the toggle option to false for this operation.

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

Retrieve the value from a variable located outside an API function call

As I work on developing a chat application project that includes abusive text detection, I have encountered an issue with accessing data from the Perspective API. While I am able to set attributes within the API function, I face challenges accessing them o ...

``There appears to be an issue with the functionality of the jQuery

I've been experimenting with using AJAX in a PHP form, but for some reason it's not working as expected. I'm at a loss trying to figure out why. Here is my code: <!DOCTYPE html> <html lang="es"> <head> <title>< ...

Problem encountered with JavaScript getter on iOS 5

While implementing JavaScript getters in my iPad-optimized website, everything was working perfectly until I updated to iOS 5. Suddenly, the site stopped functioning properly. After thorough investigation, I discovered the root cause of the issue. I have ...

Firebase Operation Not Supported Error in next.js (auth/operation-not-supported-in-this-environment)

After successfully deploying a Next.js app hosted on Vercel with Firebase authentication that functions properly for users, I encountered a mysterious error during the "npm run build" phase: FirebaseError: Firebase: Error (auth/operation-not-supported-in ...

Creating a mesh parallel to the xy-plane in Three.js

Looking to brush up on my CG fundamentals. How can I create a mesh (such as a circle) that is perfectly parallel to the xy-plane in the direction the camera is facing? For instance, I want it to be normal to the direction the camera is facing and not tilt ...

Using dynamic classes within a v-for loop

Edited How can I dynamically assign classes to multiple elements within a v-for loop? Since I cannot utilize a computed property due to the presence of v-for, I attempted using a method by passing the index of the element, but that approach did not yield t ...

Examples of Javascript closures in action with a for loop

I decided to stop my research here. Below is the question I have: After reading this post, I grasped the concept illustrated by the code snippet provided. var funcs = {}; for (var i = 0; i < 3; i++) { // creating 3 functions funcs[i] = functi ...

What is the best way to structure a JSON data string for transmission from a WebView to JavaScript?

Seeking a solution for passing multiple values from an Android WebView to JavaScript. The challenge is that the string received in JS appears completely raw with control characters. The specific issue arises when sending the following string from Java: f ...

Capable of generating an ajax URL parameter conditionally for utilization with jQuery Validate

I am having an issue with my jQuery validation script. What I am trying to achieve is this: when a user clicks the send button, the script will determine whether to execute an if or else statement based on the last portion of a string (isAdd). Subsequently ...

Organizing NodeJS modules in a way that mirrors Maven's groupId concept

I am making the switch to NodeJS after working extensively with Maven. In Maven, we are familiar with the groupId and artifactID, as well as the package name when starting a new project. However, in NodeJS, I only see a module name. The concept of groupI ...

Updating the styles of React Native components using stylesheets

I've created a unique React component with the following structure: import { StyleSheet } from 'react-native'; import { Input, Item } from 'native-base'; import Icon from 'react-native-vector-icons/FontAwesome'; import { ...

Is it possible to set up an automatic redirection to the Identity Provider sign-in page when accessing a protected page in Next.js using Auth.js?

Currently in the process of developing a web platform utilizing [email protected] and Auth.js([email protected]). The provider has been configured with the given code, allowing successful signing in using the "Sign in" button. auth.ts import Ne ...

The not:first-child selector targets all elements except for the first one in the sequence

This is a simple js gallery. I am using not:first-child to display only one photo when the page is loaded. However, it does not hide the other photos. You can view the gallery at this link: (please note that some photos are +18). My objective is to hide ...

What location is ideal for making API calls with React and Redux-thunk?

After extensively searching on StackOverflow.com and across the internet, I couldn't find a similar question. Therefore, please refrain from giving negative reputations if you happen to come across one as I truly need reputation at this point in my li ...

How to eliminate a hyperlink from an HTML element with the help of JQuery

Recently, I was assigned to revamp a website for the company I work for. However, upon closer inspection, I realized that the website is quite messy and relies heavily on templates, resulting in certain elements being auto-generated as active links. The i ...

Angular8: Stay Updated with Real-Time Data Refreshment

I've implemented code in my app.component to retrieve all users. I'm facing an issue where if I have two windows open and perform any CRUD actions, the second window displays outdated data. To address this, I am attempting to refresh the page ev ...

My JavaScript code is not triggering during the page load. Could this be related to .net

I've been attempting to trigger a JavaScript function upon the refresh of an update panel, but for some reason it's not working. Oddly enough, I'm using the same approach that has worked for other functions. In C#, this is what I have in th ...

Troubleshooting: Why is Spring MVC failing to return results on ajax call?

I am trying to retrieve user data through an ajax request, but I am facing an issue where the success part of the request is not being reached and no logs are being generated. This is the controller code: @Controller @RequestMapping(value = "/api/profile ...

The performance of HTTP requests is significantly decreased in Internet Explorer compared to expected speeds

I am currently developing an Angular site where I need to send a significant amount of data (approximately 1 MB) in an API call. In the Chrome and Firefox browsers, everything works smoothly and quickly, with a response time under one second. However, whe ...

Tips for clearing form validation errors on dynamically populated fields using data stored in localStorage

Currently, I have a form that requires validation. The desired behavior is for the form to display an error message ("this is required") and disable the submit button if any of the input fields are left empty. The validation works correctly as intended, bu ...