What is the method for condensing content using a Bootstrap toggle button (checkbox)?

Incorporating Bootstrap 5.1, I have a set of buttons that trigger the display or hide some content using the collapse plugin

    <div class="col m-2">
         <button type="btn" class="btn btn-outline-primary m-1" 
data-bs-toggle="collapse" data-bs-target="#focus_id">Focus
         </button>
    </div>
 

Nevertheless, there is no visual indication for users when a button is activated or not. I want the buttons to function as toggle switches. According to the documentation, this can be achieved by setting

data-bs-toggle="button"

However, I already use this attribute to hide/show content with

data-bs-toggle="collapse"

How can I incorporate both functionalities? I attempted

   data-bs-toggle="button,collapse"

but it did not yield the desired results

Update

I followed David's suggestion but encountered difficulty in maintaining the toggle. Instead, I renamed the button and added the following Javascript snippet to the page

let movementsSection = document.getElementById('movements_id')
let movementsButton  = document.getElementById('show_movements_button')
if(movementsSection!=null)
{
    movementsSection.addEventListener('show.bs.collapse', function() {movementsButton.innerText='Hide Movements';});
    movementsSection.addEventListener('hide.bs.collapse', function() {movementsButton.innerText='Show Movements';});
}

This solution functions adequately, except for the hardcoded button names in the Javascript, which could pose challenges during internationalization of the code

The html code is dynamically generated, while the Javascript is not. It would be advantageous to implement a solution within the html itself

Answer №1

There is currently no visual indication for the user to know if a button has been clicked.

Actually, the visibility of the collapsible section should serve as a clear indicator!

But, since both components share the same attribute, a manual approach might be the most practical and easiest for maintenance. You can achieve this by adding an event listener to your collapsible section:

let collapsibleSection = document.getElementById('mySection');
let toggleButton = document.getElementById('myButton');
collapsibleSection.addEventListener('hidden.bs.collapse', function() {
    if (toggleButton.classList.contains('my-active-css-class') {
        toggleButton.classList.add('your-inactive-css-class');
        toggleButton.classList.remove('your-active-css-class');
    }
});
collapsibleSection.addEventListener('shown.bs.collapse', function() {
    if (toggleButton.classList.contains('my-inactive-css-class') {
        toggleButton.classList.add('your-active-css-class');
        toggleButton.classList.remove('your-inactive-css-class');
    }
});

It's important to note that these events are triggered after the transition is complete. If you want your code to react immediately after the button click, use the show.bs.collapse and hide.bs.collapse events instead. Refer to the relevant documentation; however, keep in mind that method calls on a transitioning component will be ignored (see docs).

Answer №2

To address the initial concern you raised:

There is currently no visual indication for the user when a button has been clicked

We can implement a solution using only CSS

button.collapsed:focus:not(:active) {
      background-color: navy;
}

In regards to changing the text/label of the button - this is a more complex task that may require creating a custom element. As @Davide mentioned. The desired functionality is not readily available with bootstrap. Davide's code is correct and involves declarations followed by two functions, one starting with 'collapsibleSection.addEvent...'. These functions essentially add Event Listeners which wait for specific triggers, such as 'hidden.bs.collapse', and then execute the specified code.

Regarding the adequacy of this solution - your requirements are quite demanding, especially if you need the button label to be dynamically internationalized.

One potential approach is to include HTML elements with the desired labels, and then use JavaScript to swap them based on certain triggers - essentially a more advanced version of Davide's suggestion.

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

Restricting the input on a React component to only accept alphabet characters from A to Z instead of allowing any keyboard

I am currently facing a challenge with understanding a specific component, particularly the allowForClassification value. This boolean value is passed down to a child component and decides whether a button is displayed or not. The issue arises when tryin ...

Inquiry regarding the ng-disabled directive in AngularJS

<div ng-app="myApp" ng-controller="myCtrl"> <button type="submit" class="btn btn-primary pull-left" ng- disabled="captchaError">Submit</button> </div> <script> var app = angular.module('myApp', []); app.controller( ...

Styling buttons with different colors using React onClick event.getSelectedItem() method

I am having an issue with adding a border when the class is set to "transportation active" in my React code. When I click on one of the icons, all of them become active instead of just the clicked one. This behavior is not what I want, as I only want the ...

What is the best way to update a specific section of my website by modifying the URL while keeping the menus fixed and the site functioning smoothly?

I am in desperate need of assistance as I search for a solution. Currently, I am working on a project involving music within a web browser or application. My goal is to utilize HTML, PHP, JS, and CSS to create this project. If I start with a website, I p ...

How can you make the browser window scroll horizontally when a div is clicked using jQuery?

I have an image of an arrow inside a div. The div is positioned fixed in the bottom right corner of an extremely wide page. Is there a way to utilize jQuery to scroll the window 600px to the right each time the arrow is clicked? Also, can I detect when th ...

The final child element is null when using lastElementChild

For my current Javascript project, I am tackling the task of dividing the page into two separate div elements. The left div is populated with randomly positioned images, and then I utilized the .cloneNode() method to duplicate this on the right side, exclu ...

Updating content with jQuery based on radio button selection

Looking for assistance with a simple jQuery code that will display different content when different radio buttons are clicked. Check out the code here. This is the HTML code: <label class="radio inline"> <input id="up_radio" type="radio" n ...

Is there a way to access the value of a variable in Express that is stored in a different file?

Looking for a way to fetch the value of a variable that is located inside app.use? chatbot.js: const express = require('express'); const app = express.Router(); app.use(['/chat', '/chatbot'], (req, res, next) => { const ...

Utilizing Polymer 3 in a different context such as ASP.NET MVC allows for the development of versatile components known as PolymerElements that can be reused

I am currently working on integrating Polymer 3 components into my ASP.NET MVC application. I'm not entirely sure if my approach to this issue is correct at the moment. My main goal is to execute everything from IIS Express. However, I'm encou ...

Eliminate all key-value pairs from an array of objects except for the specified key-value pair

I've got an array filled with objects const myArr = [ {k1: 1, k2: 1, k3: 3, k4: 4}, {k1: 1, k2: 2, k3: 3, k4: 4}, {k1: 1, k2: 2, k3: 3, k4: 4}, {k1: 1, k2: 2, k3: 3, k4: 4} ] I'm attempting to filter these objects, although I don&apos ...

Prevent selection of rows in the initial column of DataTables

I am working on a basic datable, the code can be found here JS: var dataSet = [ ["data/rennes/", "Rennes", "rennes.map"], ["data/nantes/", "Nantes", "nantes.map"], ["data/tours/", "Tours", "tours.map"], ["data/bordeaux/", "Bordeaux", ...

Vue in d3 - the property ownerDocument is not defined

I'm currently working on integrating d3 charts with Vue. I've noticed that using a ref seems to trigger an error, but is that the correct approach? <template> <div ref="chart"></div> </template> const char ...

Is it possible to invoke a JavaScript function within PHP code?

When setting up server side validations on my login form, I want to display error messages directly below the validated control when an error occurs. However, I am currently having trouble calling a JavaScript function from my PHP code to handle this. < ...

Implementation of internationalization into a JSON-formatted data file

I recently integrated i18n into my application and I'm facing a challenge with implementing the useTranslation(); function in my navbar data file. This file serves as the database for the page titles and tabs, and I'm unsure about how to proceed. ...

The getElementById method in JavaScript can result in a null return value

Why is null returned by the getElementById method in JavaScript? <html> <head> <title>test_elementObject</title> <script language="JavaScript" type="text/javascript"> <!-- var input1 = document.getElementById ( " ...

Numerous routers available for enhancing functionality in an Ember application

Can an Ember app have multiple router.js files? By default, one router.js file will look like this: import Ember from 'ember'; import config from '../../config/environment'; var Router = Ember.Router.extend({ location: config.locat ...

Connecting JSON objects based on unique GUID values generated

I am in search of a method to automate the laborious task of linking multiple JSON objects with random GUIDs. The JSON files are all interconnected: { "name": "some.interesting.name", "description": "helpful desc ...

Why does the Node.js REST API keep throwing errors after I try to create just one record?

I encountered a back end issue recently. I have developed a simple API with just a post endpoint. The intention is to post data using the req.body. Oddly enough, it works perfectly fine the first time but when I attempt it again, I receive an error message ...

Error in Blinking Tooltip when Hovering Skill Bubble (React and d3)

I've encountered a frustrating issue with tooltips on my website - they just won't stop blinking when I hover over the skill bubbles. I tried fixing the tooltips at a certain location, but whenever there's a bubble in that spot and I hover o ...

Strategies for resolving minor validation challenges (Almost complete, just a few finishing touches needed ...)

This question was originally posted in Spanish on es.stackoverflow.com by Julian Dumitrel: I had planned to make a record, step by step, where I had 3 different steps all within one <form>. After finishing my form validator successfully, I encounte ...