Issue arises when incorporating accordion toggle with navtabs (Bootstrap)

Currently, I am working on a navigation layout using Bootstrap that will be displayed as tabs on desktop and as an accordion on mobile devices. The setup is almost complete, but there is an issue that I'm struggling to resolve.

The problem arises when I click on a tab (let's say Link #3) in the desktop version and then switch to the mobile view. The correct tab (Link #3) opens, but if I try to close the tab by clicking on it, the content gets hidden while the button and toggle icon remain in the "open state." This issue can be observed on desktops or tablets which display the nav-tabs. To see the problem on your desktop, simply decrease the viewport size after selecting a nav tab.

I initially attempted to track the visibility of the content using 'classList.contains()' to control the open/close functionality. However, I realized that this method only works when the class is mentioned inline. If not specified inline, the function fails to keep track of the classes even though Bootstrap internally toggles between them. It seems like my usage of the contains function might be incorrect, or perhaps I overlooked something.

I also explored the idea of tracking clicks on the nav-tabs and accordions to add/remove the 'collapse' class accordingly. However, this approach interferes with other scenarios where the toggle function operates correctly.

Unfortunately, utilizing the toggle() function for Bootstrap accordion's 'collapse' or 'show' features did not yield the desired results either.

After experimenting further, I managed to make .contains() work but had to introduce a recursive function to handle the toggling of the 'collapsed' class, resulting in performance issues and unresponsiveness on the page.

// JavaScript code snippet goes here
.container .nav-tabs {
  display: none;
}

/* MEDIA QUERY */
@media screen and (min-width: 992px) {
  .container .nav-tabs {
    display: flex;
  }
  .accordion-item h2 {
    display: none;
  }
  .container .accordion-item {
    border: none;
}
// HTML code snippet goes here

Answer №1

Initially, I faced challenges when attempting to resolve this issue, but after conducting a thorough investigation, I was able to successfully address it. Here are the primary modifications that were implemented to solve the problem:

// Addressing visibility issues with tab content on Desktop  

const mediaQuery = window.matchMedia('(min-width: 992px)');
  
  // Adding the show class to display content when the active class is present
  window.addEventListener('resize', function(){
    if (mediaQuery.matches) {
      document.querySelectorAll('.accordion-collapse').forEach(function(item){
        if(item.classList.contains('active')){
          item.classList.add('show');
        }
      })
    }
  })

Furthermore, I identified and rectified an additional issue in your JavaScript code at two different junctures. The use of querySelectorAll did not incorporate an iteration method for the elements retrieved.

document.querySelectorAll('.accordion-button').forEach(function(item){
    item.addEventListener('click', contentVisible());
})

function myFunction(x) {
    if (x.matches) { 
        document.querySelectorAll('.nav-link').forEach(function(item){
            item.addEventListener('click', callTab());
        })
    }
}   

Next, the JavaScript snippets provided below detail how certain functions were corrected and optimized to ensure smooth operation of the intended functionality.

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

Having trouble with Vue image source file paths?

Having an issue with loading an image via file_path on Vue. When using a hardcoded path, it works fine. Refer to the sample code below: JavaScript function getRestaurantsbyId(id) { var restaurants = { "1" : { "name": "xxxx", ...

Executing a JavaScript function with jQuery

function launch() { $("p").text("Hey there", greet()); } function greet() { alert("Greetings! You have triggered another function"); } HTML: <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button onclic ...

Error: null does not have the property 'renderView' to be read

My goal is to set up a main page in React.js with two buttons: Option 1 and Option 2. Clicking on Option 1 should redirect the user to the Main1 page, while clicking on Option 2 should lead them to Main2. It seems straightforward, but I am encountering the ...

Adding a character at the current cursor position in VUE JS

My quest for inserting emojis in a textarea at the exact cursor position has led me to an extensive search on Vue JS techniques. However, most resources available online provide solutions using plain Javascript. Here is the code snippet I am working with: ...

Apply a specific CSS class to a division depending on the currently active cookie

I have implemented cookies on specific pages using https://github.com/carhartl/jquery-cookie. Could someone guide me on how to apply a CSS class to an ID (e.g., adding class .red to #mouse if the cookie named "socks" is active)? For example: If there is ...

Utilizing external directory files in electron-packager during the packaging process

I am currently in the process of packaging my electron application, which consists of two npm directories nested within each other. The inner directory contains my electron app and relies on scripts located in the outer directory. In my internal package. ...

How to Divide a String at the Second-to-Last Instance of a Comma Using jQuery

Imagine having a string like this: var str = "xy,yz,zx,ab,bc,cd"; If you wish to split it at the second-to-last comma occurrence, resulting in: a = "xy,yz,zx,ab" b = "bc,cd" How can one accomplish this task? ...

When working on my asp.net webform, I incorporated an AgreementCheckBox along with a CustomValidator. However, I encountered an issue where the error message

Code for AgreementCheckBox: <asp:CheckBox ID="AgreementCheckBox" runat="server" ForeColor="Black" Text="Please agree to our terms and conditions!" /> Code for AgreementCustomValidator: <asp:CustomValidator ID="AgreementCustomValidator" runat=" ...

Understanding the difference between Parameters in Javascript and Java

Currently, I am facing an issue where I am losing some information while sending an ajax request to a servlet. The specific parameter that I am losing data from is the "comment" parameter. Below are the last 4 lines of my ajax code: var params = "name=" + ...

Integration of a QR code scanner on a WordPress website page

I'm in the process of setting up a QR code scanner on my Wordpress site or within a popup. The goal is for users to be able to scan a QR code when they visit the page/popup link. Specifically, the QR code will represent a WooCommerce product URL, and ...

What can I do to prevent my panolens.js image from pausing its spin whenever a user clicks on it?

I've been working on setting up a 360 image background that rotates automatically and disabling most user interaction controls. However, I'm struggling with one issue – preventing any form of interaction from the user altogether. Whenever a use ...

What is the process for activating an event when a window undergoes a change?

I created a window using the window.open method to display a form. Once the user submits the form, they are redirected to a page called success.html. Is there a way to trigger an event after success.html finishes loading? I attempted the following approach ...

The parameter in a JavaScript for loop

I'm struggling with my Javascript skills. Here is the code snippet I am currently working with: var information = [ {"Column":"","keyw":"","Column_3":"day of march 2011 to someother numeric" ...

CSS- Strategically placing and centering images above specific keywords in (any) HTML content without disrupting the flow of text

My main objective involves dynamically inserting images above text on any given page using a content script. The challenge lies in maintaining the proper alignment of the text after adding the images. To achieve this, I surround the words where the image i ...

Learn how to utilize the Page props in the getServerSideProps method with Next.js

I have passed some properties to the _app page. <PageWrapper> <Component someProps={someProps} /> <GlobalCSS /> </PageWrapper> Can these props be accessed in the getServerSideProps method on each individual Page? export const g ...

Line breaks in Vue v-tooltip functionality

Currently, I am implementing v-tooltip to add tooltip text to a button. My aim is to include a line break within the tooltip text, but I have been unable to determine if this is feasible using this method. After reviewing the documentation, I did not find ...

Restricting user access to a route based on its type to enhance security and control

Currently, I have a React, Redux, and Next.js app up and running. Within my redux store, there is a user object that contains an attribute called "type". Each type of user has its own set of "routes" they are allowed to access. I am looking for the most e ...

What happens when arithmetic operators are applied to infinity values in JavaScript?

Why do Arithmetic Operators Behave Differently with Infinity in JavaScript? console.log(1.7976931348623157E+10308 + 1.7976931348623157E+10308)//Infinity console.log(1.7976931348623157E+10308 * 1.7976931348623157E+10308)//Infinity console.log(1.797693134 ...

Navigate to a different webpage while employing sweetalert2 and extracting data using the GET method

Is there a way to use sweetalert2 for redirecting to deleting.php with a specific ID parameter? How can I include this dynamic data in the code snippet below, which is used to display options for editing and purging data from an SQL database? echo' &l ...

Utilizing Raycaster for modifying the Box's face color upon clicking

I've been experimenting with the raycaster in order to select faces of cubes that are created, and then change the color of the clicked face. So far, I've managed to make it work for selecting entire objects, but not individual faces of those obj ...