Ways to stop Bootstrap collapse from displaying depending on a certain condition in bs5 framework

I've been struggling to figure out how to prevent a collapsible panel from opening or showing if a specific value is null. Despite multiple attempts, I haven't had any success.

HTML

<a href="#" data-bs-toggle="collapse" data-bs-target="#infoBox" aria-expanded="false" aria-controls="infoBox"></i>
  
<div class="collapse m-3" id="infoBox">some ifos ...</div>

First attempt:

var someVal;
var infoBox = document.getElementById('infoBox')
infoBox.addEventListener('show.bs.collapse', function () {
    // console.log(e.target);
    if (someVal == null) return;
})

Second attempt:

var someVal;
var infoBox = document.getElementById('infoBox');
var bsCollapse = new bootstrap.Collapse(infoBox, {
    show: false,
    dispose: true
})
infoBox.addEventListener('show.bs.collapse', function (e) {
    // console.log(e.target);
    if (someVal == null) return bsCollapse;
})

Unfortunately, neither of these methods seem to be effective.

Answer №1

To prevent the default action, make sure to use the e.preventDefault() function.

var toggle = false;

$("#wrapper").on('show.bs.collapse', function (e) {
    if (!toggle) {
      e.preventDefault();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d7f7272696e696f7c6d5d28332c332e">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="14767b7b60676066756454213a253a27">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">


<div id="wrapper">
  <a href="#" data-bs-toggle="collapse" data-bs-target="#infoBox" aria-expanded="false" aria-controls="infoBox" id="myCollapsible">press me</a>

  <div class="collapse m-3" id="infoBox">some information ...</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

Navigating JSON Data in Groovy Using a Loop: A Handy Guide

Just starting out with Groovy and attempting to mock a service in SoapUI. The task at hand involves loading a text file containing JSON data, and then matching that data to a specific node. Here is what I have attempted so far: def inputFile = new File( ...

The issue of responsive spacing (such as mb-lg-2 mb-sm-3, etc) not functioning as expected has been identified in Bootstrap

Previously in Bootstrap 4, these classes were effective. However, I am finding that they are not functioning properly in Bootstrap 5. Any insights as to why this might be happening? Note: d-block d-lg-flex , text-center text-lg-start text-md-end seem to s ...

Transforming a value within a controller into a directive

I am uncertain if I am approaching this correctly, but my goal is to convert a piece of code from a controller to a directive. The reason for this change is that I want to reuse the code with different values without creating multiple large object literals ...

A guide on fetching the selected date from a datepicker in framework7 with the help of vuejs

Here is a snippet of the code for a component I am working on: <f7-list-input label=“Fecha de nacimiento” type=“datepicker” placeholder=“Selecciona una fecha” :value=“perfil.fecha_nacimiento” @input=“perfil.fecha_nacimiento = $event.t ...

Create a dynamically updating list using React's TypeScript rendering at regular intervals

My goal is to create a game where objects fall from the top of the screen, and when clicked, they disappear and increase the score. However, I am facing an issue where the items are not visible on the screen. I have implemented the use of setInterval to d ...

Stop JQuery from executing when an error is caught

Once the document is ready, I have configured: $.ajaxSetup({ "error": function (XMLHttpRequest, textStatus, errorThrown) { if(XMLHttpRequest.status == 403) { display_modal( 'Please login to continue.', &ap ...

Error: Trying to use 'search' before it has been initialized causes a ReferenceError

Every time I run my code, I encounter this reference error but I can't figure out what's causing it. ReferenceError: Cannot access 'search' before initialization App C:/Users/GS66/Desktop/IN20/IFN666/week4/src/App.js:60 57 | 58 | expor ...

The changing of colors does not function properly when clicked in JavaScript

I am having an issue with a drop-down list that offers two options: blue and green. When I select blue and click on the text input field, its background color alternates between blue and black (the default text field color). The same applies when I choose ...

Revolutionizing user experience: New feature seamlessly triggers button actions with the power of "enter"

I need assistance with modifying a form that contains two buttons and several text inputs. Currently, if the enter key is pressed, it triggers a click event on the first button. However, I want to modify this behavior so that if any of the text boxes are f ...

Hear and register keypress in Angular service

I offer a dialog service Check it out below @Injectable() export class HomeDialogService { public constructor(private readonly dialogService: DialogService, private readonly userAgent: UserAgentService) {} @HostListener('document:keydown.escape ...

When a fetch request is called inside a map function in React, the return

I attempted to retrieve a map array through fetch resolves so that each element inside favoriteCards would return a value and assign it to the test variable useEffect(() => { const test = favoriteCards.map((card) => { accuWeatherApi.getCurrentW ...

execute various scripts in content_scripts depending on the "matches" provided

I am new to JavaScript and currently working on customizing the script from the MDN tutorial, Your First WebExtension My goal is to draw either a red or blue box around a webpage based on whether it is http:// or https://. But I have encountered a proble ...

Sorting data in Javascript can be done efficiently by utilizing the .filter method

Can someone help me identify what I might be doing incorrectly? I have a chained filter under computed that is giving me an error message stating 'product.topic.sort' is not a function. My intention is to use 'select' to provide sortin ...

Trouble with minification in Sencha cmd 5

I've been attempting to compress a Sencha 5 project using Sencha CMD, but I keep experiencing failures. sencha generate app -ext demoApp ./demoApp Then, in an effort to compress the application, I entered the following command: sencha app build ...

I recently developed a T3 stack project and am currently attempting to configure a next JS middleware, however, I am encountering issues with it not triggering as expected

Having issues with my T3 stack app where the next js middleware is not triggering. I've placed a middelware.ts file in the root directory. middleware.ts // middleware.ts import { NextResponse } from "next/server"; import type { NextRequest ...

Error: The PDFJS variable is not recognized when trying to load a PDF file

I've been experimenting with pdf.js to load PDFs into a web application in order to extract information in real-time. However, I keep encountering an error even with a simple example. I've attempted enclosing the code in $(document).ready() as a ...

Utilizing ID for Data Filtering

[ { "acronym": "VMF", "defaultValue": "Video & Audio Management Function", "description": "This is defined as the Video and/or Audio Management functionality that can be performed on a Digital Item. The Video & Audio M ...

Guide to configuring Javascript as a Blade template for integration into an API endpoint

I am currently developing a Javascript program that is loaded through an external include. Here's how it looks: <!DOCTYPE html> <html lang="en"> <head> ... </head> <body> ...html code goes here... & ...

Exploring Multilingual Autocomplete or: Best Practices for Managing Multiple Languages in Web Applications

I'm currently developing a website and I have a mysql-table named 'items' with the following structure: item_id | item (The second column is used to identify the item_id.) In a file called language1.php, I have an array that stores the it ...

Encountering issues with Node.js and Socket.io not displaying results on Internet Explorer when using a secure connection

I have successfully integrated socket.io, node.js, and express to serve real-time json data to multiple browsers except for IE (tested on version 9) over a secure connection. Everything was functioning smoothly until I switched to HTTPS. From the server&ap ...