Is there a way to postpone the collapse functionality in Bootstrap?

Is there a way to delay the display of collapsed elements in Bootstrap 4?

For instance, how can you postpone the content of a Link href button from appearing in the example provided below?

<p>
  <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
    Link with href
  </a>

<div class="collapse" id="collapseExample">
    <div class="card card-block">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus          richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes          anderson cred nesciunt sapiente ea proident.
    <div>
</div>

Answer №1

If you want to customize the collapse behavior in my solution, you have the option to utilize the data-delayed-toggle and data-delay attributes on the trigger element:

$('[data-delayed-toggle="collapse"]').on('click', function(e) {

      var delay = $(this).data('delay') || 1000;
      var $target = $($(this).attr("href"));

      window.setTimeout(function() {
        
        if ($target.hasClass('show'))
            $target.collapse('hide');
         else
            $target.collapse('show');
          }, delay);

      })
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>

<p>
  <a class="btn btn-primary" data-delayed-toggle="collapse" href="#collapseExample" data-delay="300">
    Link with href
  </a>
  <div class="collapse" id="collapseExample">
    <div class="card card-block">
      Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
      < div>
    </div>

Answer №2

The CSS animations are achieved with the use of CSS and the jQuery library to switch CSS classes dynamically.

If a slight delay is desired, the transition-delay: property can be applied to the .collapsing class. For instance, a delay of 2 seconds can be implemented as shown below.

.collapsing {
    -webkit-transition-delay: 2s;
    transition-delay: 2s;
    visibility: hidden;
}

Subsequently, Bootstrap's JavaScript will trigger and add the .show class to the element. To prolong the delay in visibility, an additional delay can be added to the .collapse.show class...

.collapse.show {
    -webkit-transition-delay: 3s;
    transition-delay: 3s;
    visibility: visible;
}

Answer №3

This snippet of code provides the capability to manually set a delay or use another function to control transitions and ensure they do not execute until you are ready.

var delay = false,delayed=900;
$('[role="button"]').on('click', function (e) {  
  var $this = $(this),
      href,
      target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, ''), //strip for ie7
      $target = $(target),
      data = $target.data('bs.collapse'),
      option = data ? 'toggle' : $this.data(),
      parent = $this.attr('data-parent'),
      $parent = parent && $(parent);

  if (!delay) { 
    setTimeout(()=>{delay=true; $target.collapse(option); delay = false }, delayed); 
    return false;
  }   

  if (!data || !data.transitioning) {
    if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed');
    $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed');
  }

  $target.collapse(option);
})

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

Integrating Whatsapp cloud API with a React web application allows for seamless communication between

I'm currently in the process of integrating my web application with the WhatsApp cloud API. While I've had success sending test messages, I am now looking to incorporate variables as outlined in the API documentation. However, I seem to be encoun ...

When a page with parameters is reloaded, React fails to initiate

I'm encountering an issue with my application in development mode on localhost. When I try to reload the app on a route with parameters, for example: localhost:8080/item/2 React fails to initialize and only a blank page is displayed. However, if I ...

When using Node.js with Express and ssh2, my data structures remain intact without any resets when loading web pages

To display jobs sent by users to a cluster, the code below is used (simplified): var split = require('split'); var Client = require('ssh2').Client; var conn = new Client(); var globalRes; var table = [["Head_1","Head_2"]]; module.exp ...

Is there a built-in constant in the Angular framework that automatically resolves a promise as soon as it

I'm facing a situation where I have code that checks a conditional statement to decide if an asynchronous call should be made. If the condition is not met, the call is skipped. However, I still need to perform some final action regardless of whether t ...

Aligning content vertically in Bootstrap 4 so it is centered

I've been struggling to center my Container in the middle of the page using Bootstrap 4. I haven't had much luck so far. Any suggestions would be greatly appreciated. You can check out what I have so far on Codepen.io and experiment with it to s ...

Sequelize - utilizing the where clause with counting

I have three models that extend Sequelize.Model and I have generated migrations for them. The associations are set up as follows: Cat Cat.belongsToMany(Treat, { as: 'treats', through: 'CatTreat', foreignKey: 'cat_id', } ...

Executing Firebase Cloud Functions to perform write operations within a database event function

Exploring the world of Firebase functions has been an exciting learning journey for me. This innovative feature is proving to be incredibly powerful and beneficial. I'm eager to utilize a function that can capture a database writing event, perform a ...

Tips for determining what elements are being updated in terms of style

I need assistance with modifying the functionality of a webpage's dropdown menu. Currently, it displays when the mouse hovers over it, but I want to change it to appear on click using my own JavaScript. Despite setting the onmouseout and onmouseover e ...

Errors are not displayed or validated when a FormControl is disabled in Angular 4

My FormControl is connected to an input element. <input matInput [formControl]="nameControl"> This setup looks like the following during initialization: this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, U ...

Error: The `Field` component encountered a failed prop type validation due to an invalid prop `component` after upgrading to MUI version

Encountered an error when migrating to Material ui v4 Failed prop type: Invalid prop component supplied to Field. in Field (created by TextField) This error points to the redux form field component export const TextField = props => ( <Field ...

"Submit form data without reloading the page using the $_

I have an associative array that I am using to display images. I want to randomly select two or more pictures from these images with my code, but I have a couple of questions: How can I enhance the efficiency of my code? And is there a way to use JSON or ...

Change the spread operator in JavaScript to TypeScript functions

I'm struggling to convert a piece of code from Javascript to Typescript. The main issue lies in converting the spread operator. function calculateCombinations(first, next, ...rest) { if (rest.length) { next = calculateCombinations(next, ...res ...

Navigate to the final element of a mapped array

My current project includes a Message component that showcases all messages, whether incoming or outgoing, within a single thread. One feature I am aiming to implement involves ensuring that the most recent message, a freshly typed one, or an incoming mes ...

Retrieve a string value in Next.JS without using quotation marks

Using .send rather than .json solved the problem, thank you I have an API in next.js and I need a response without Quote Marks. Currently, the response in the browser includes "value", but I only want value. This is my current endpoint: export ...

Even though the onSubmit attribute is set to false in the HTML form, it still submits

I've been struggling with a form that just won't stop submitting, no matter what I do. I have checked similar questions on SO, but none of the solutions seem to work for me. It's frustrating because it's such a simple task. The reason w ...

Steps for designing an HTML table that expands and collapses partially

I am currently revamping an old "Top Screens" page by expanding the display from the top 30 to the top 100 in a basic html table format. However, I only want to show the top 20 on page load with an expand/collapse feature. While I have come across examples ...

Using Jquery Ajax to Develop Laravel Dropdown Selection with Cascading Feature

I have been working with Laravel 5.6 and encountered an issue with my dropdown selection. Although I selected a province from the dropdown menu, the city menu did not display the corresponding cities. Below is the controller code that I am using: public f ...

When attempting to duplicate a project from Bitbucket and working in VS Code, I encountered several errors and warnings while running npm install

I have a project on Bitbucket that I'm trying to clone. The project is quite old, about 3 years old, so some packages may be outdated. However, when I run npm install, I am seeing a lot of warnings and errors. Additionally, the project was originally ...

Transform a JavaScript Array into a JSON entity

Currently working on a Mail Merge project using Google Apps Script, I've encountered an issue with displaying inline images in the email body. After sending the email using GmailApp.sendEmail(), all inline images are shown as attachments instead of be ...

The functionality of Jquery autocomplete _renderItem appears to be malfunctioning

There seems to be an issue with the _renderItem function as it is not executing at all. I even tried using console.log to debug but no messages are being printed. I also attempted using various attributes like 'autocomplete', 'ui-autocomplet ...