Is there a way to repurpose a displayed.bs.collapse function for multiple uses?

I have implemented a JavaScript snippet that enables a collapse feature with color and chevron changes based on its open or closed state. Now, I am attempting to replicate this functionality for a different button but haven't had success by changing the IDs and class names as expected.

$('#accolades').on('shown.bs.collapse', function() {
    $(".js-chevron").addClass('fa-chevron-up').removeClass('fa-chevron-down');
    $(".js-button").addClass('button-accolades').removeClass('btn-outline-light');
  });
$('#accolades').on('hidden.bs.collapse', function() {
    $(".js-chevron").addClass('fa-chevron-down').removeClass('fa-chevron-up');
    $(".js-button").addClass('btn-outline-light').removeClass('button-accolades');
  });

Is there a way to reuse this code for multiple instances so that each instance acts independently of the others?

Thank you in advance!

Answer №1

Have you considered encapsulating the two definitions within another function? Then applying it to each item group?

// Function Definition
const applyCollapseAction = (container, chevEl, btnEl) => {
  container.on('shown.bs.collapse', function() {
      chevEl.addClass('fa-chevron-up').removeClass('fa-chevron-down');
      btnEl.addClass('button-accolades').removeClass('btn-outline-light');
    });
  container.on('hidden.bs.collapse', function() {
      chevEl.addClass('fa-chevron-down').removeClass('fa-chevron-up');
      btnEl.addClass('btn-outline-light').removeClass('button-accolades');
  });
};

// Function Calls
applyCollapseAction($('#accolades'), $(".js-chevron"), $(".js-button"));
applyCollapseAction($('#accolades2'), $(".js-chevron2"), $(".js-button2"));

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

What causes padding/margin when using overflow: hidden?

Today, I came across a peculiar issue. Adding the overflow: hidden style to a div seems to create extra blank space around its header content, resembling margin or padding. While this might go unnoticed in most cases, it's causing a problem with an an ...

Can default query parameters be predefined for a resource in AngularJS?

When working with a simple resource like the one defined below, it is possible to utilize the Receipt.query() method to retrieve a collection from the server. In addition, by calling Receipt.query({freightBill: 123}), a query parameter such as freightBill ...

javascript: update hidden field if date is past January 15th

Having a bit of trouble with this one after a full day! The form contains a hidden field called 'grant_cycle'. If the form is submitted after January 15th, it should have the value 'Spring, [year]', or if after July 15th, it should be ...

Notification access is consistently denied

In my coding work, I rely on Notification.permission to determine if the browser supports notifications or not. Here's a snippet of how I handle Notification.permission in my script: // Verify browser notification support if (!("Notification" in windo ...

What is the best way to retrieve information from nested JSON objects?

Currently, I am attempting to retrieve messages in Node.js using discord.js. { "627832600865800222": { //guild id "348832732647784460": { // author id "message": "hii hello" } } } let autho ...

What is the common approach for directing a setState Redux action?

I am looking to streamline my state update actions in multiple react-redux reducers by creating a general setState action. This will allow me to have consistent syntax for dispatching both local and redux scope updates. For local updates, I would use this. ...

Difficulty arising while trying to access the following element after the designated target using JQuery

JSFiddle I'm encountering a strange issue in the fiddle linked above. When typing a character into an input followed by pressing the down key, the console logs two values: one correct value of 3, and one incorrect value of 0. The challenge is to sel ...

What is the best way to center align a Bootstrap 4 modal window?

I'm facing a small issue here, I would like to have the modal display in the center. Instead of it appearing like this https://i.sstatic.net/R518w.jpg, I want it to look like this https://i.sstatic.net/wwUo7.jpg. Here is the code: <!-- The Modal -- ...

Swapping out a Django template variable for a variable generated using JavaScript

I'm new to Django and Javascript (less than 3 weeks!) and I have a query that may seem naive, so any assistance would be appreciated. In my current code, I have an HTML table rendered with the following snippet: <table border="1" class="dataframe ...

Undefined will be returned if the data in AngularJS is not set within the $scope

I have developed a factory that contains a list of functions which are called when the state changes. On page load, I am calling dtoResource.rc1Step1DTO(). Although the function executes, when I check the result in the console, it returns undefined. Below ...

Is it possible to create personalized BBCode?

I currently manage my own forum where users can edit, delete, and report posts and replies. However, I am now looking to add new features such as BBCode. Specifically, I want to implement a [QUOTE][/QUOTE] feature that allows users to easily quote other po ...

Although everything appears to be running smoothly in Express, my request is returning null

I am facing an issue with a router in my code. In the main index.ts file, I have the following line: app.use("/api/tshirts", tshirts) And in tshirts.ts file, I have defined the following routes: router.get("/", tshirtsController.getTShirts) router.get("/ ...

Radio button default checked value remains unchanged when a different selection is made

My radio group consists of options for Male and Female. Based on the stored data in the database, I have set a default checked radio button. Upon inspecting the element, I found everything as expected: However, when I select Female, the JQuery still read ...

Issues with Jquery Checkboxes Functionality

Hi everyone, yesterday I had a question and since then I have made quite a few changes to my code. Right now, I am attempting to make some JavaScript work when a specific checkbox is checked. However, nothing is happening when I check the checkbox. Can any ...

Utilizing Fragments in Vuejs 2.x with Jsx - A User's Guide

Considering the presence of Fragments in React and the lack of a specific solution in the official Vuejs GitHub thread, what alternative methods could be used in Vuejs? This information may be beneficial for developers transitioning from a React backgrou ...

Is there a way to create a responsive navbar using flexbox that automatically transitions into two rows at smaller screen sizes?

I've designed a sleek navbar located at the bottom of my webpage featuring a central logo leading to the home page, with two links on each side directing users to specific pages. Using @media CSS, I made it responsive by reducing its size as the scree ...

"Enhancing Your Tables: A Guide to Implementing Filters in jQuery.fancyTable or Similar Tools

Currently, I am utilizing the fancyTable plugin to showcase a table of Django results. I have successfully integrated a search bar and sortable columns (ascending/descending). Filters are also incorporated, but at present, they only update the search bar w ...

Determine the quantity of items that meet specific criteria

The initial state of my store is set as follows: let initialState = { items: [], itemsCount: 0, completedCount: 0 }; Whenever I dispatch an action with the type ADD_ITEM, a new item gets added to the items array while also incrementing the count in ...

Press anywhere outside the container to conceal it along with the button

Utilizing an Angular directive to hide div elements when the user interacts outside of them has been effective. However, there is a specific issue that arises when clicking outside of a div on a button that toggles the visibility of the div. The 'ang ...

Is it possible for the Vue computed function to use destructuring assignment for the parameter even when no arguments are provided?

new Vue({ el: "#app", data: { value: "text", }, computed:{ all: function({value}){ return value } } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"> ...