Trouble with toggling class "collapsed" in Bootstrap v3 Navbar-toggle when using multiple data-targets

When using the data-target attribute with multiple CSS selectors, the behavior of toggling the "collapsed" class in navbar-toggle does not work as expected. If only one selector is used, the class is toggled properly, but when multiple selectors are specified, the class remains "collapsed." I need the class "collapsed" to change in navbar-toggle even with multiple selectors.

If anyone can provide assistance, it would be greatly appreciated.

<div id="mainNav">
<nav class="navbar navbar-inverse">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar, #userPanel" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar top-bar"></span>
            <span class="icon-bar middle-bar"></span>
            <span class="icon-bar bottom-bar"></span>
        </button>
    </div>

    <div id="navbar" class="navbar-collapse collapse">
        <ul class="nav navbar-nav">
            <li class="active">
                <a href="#">
                    <span class="navicon glyphicon glyphicon-th" aria-hidden="true"></span>
                    <span class="navtext">Dashboard</span>
                </a>
            </li>
            <li>
                <a href="#">
                    <span class="navicon glyphicon glyphicon-fire" aria-hidden="true"></span>
                    <span class="navtext">About</span>
                </a>
            </li>
        </ul>
    </div>
</nav>
</div>

<div id="userPanel" class="navbar-collapse collapse">
<ul>
    <li>Max Muster | 101945</li>
    <li><a href="#"><span class="glyphicon glyphicon-off" aria-hidden="true"></span> Logout</a></li>
</ul>

Answer №1

My approach to resolving the issue did not involve rearranging the elements:

I opted for using a class selector (".navbar-collapse") as the data-target, which worked well. However, I encountered a problem with the toggle button where the "collapsed" class was not being removed. This caused the script to be unable to locate the trigger element when multiple targets were specified.

After examining the source code on GitHub, I discovered how they search for the trigger element:

this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
                  '[data-toggle="collapse"][data-target="#' + element.id + '"]')

It became apparent that using a comma-separated list of element IDs or class selectors in the data-target property would not work. This method would iterate through all elements but not find the corresponding trigger button. Fortunately, there is a clever workaround that I have just stumbled upon. The trigger selector checks both the data-target and href attributes (using the OR logical operator), allowing us to trick it by adding a href attribute to the toggle button, pointing to an existing ID (#navbar OR #userPanel). In my sample code, I used the former:

Therefore, the solution without restructuring is as follows:

<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse" href="#navbar" aria-expanded="false" aria-controls="navbar,userPanel">
    ...
</button>

By simply modifying the trigger button's attributes, the remaining code can stay unchanged.

Answer №2

Enclose both sections in a div with an id and apply a class to both sets of data. Use the provided code snippet with the data-parent attribute to collapse both sections. Test it out and let me know if it works for you.

<div id="wraper"> 
   <div id="mainNav">
      <nav class="navbar navbar-inverse">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-parent="#wraper" data-target=".navbar_collapsed_data" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar top-bar"></span>
                <span class="icon-bar middle-bar"></span>
                <span class="icon-bar bottom-bar"></span>
            </button>
        </div>

        <div class="navbar_collapsed_data navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li class="active">
                    <a href="#">
                        <span class="navicon glyphicon glyphicon-th" aria-hidden="true"></span>
                        <span class="navtext">Dashboard</span>
                    </a>
                </li>
                <li>
                    <a href="#">
                        <span class="navicon glyphicon glyphicon-fire" aria-hidden="true"></span>
                        <span class="navtext">About</span>
                    </a>
                </li>
            </ul>
        </div>
      </nav>
    </div>

<div class="navbar_collapsed_data navbar-collapse collapse">
    <ul>
        <li>John Doe | 123456</li>
        <li><a href="#"><span class="glyphicon glyphicon-off" aria-hidden="true"></span> Logout</a></li>
    </ul>
  </div>

Answer №3

After making a few adjustments, I have reorganized the structure and grouped the collapse components into a single container. This modification proved to be effective in my scenario:

<nav class="navbar navbar-inverse">
   <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-target="#collapseArea" data-toggle="collapse" aria-expanded="false" aria-controls="navbar">
       ...
      </button>
   </div>

   <div id="collapseArea" class="navbar-collapse collapse">
       <ul id="mainNav" class="nav navbar-nav">
          <li>...</li>
          <li>...</li>
       </ul>

       <div id="userPanel">
           <ul>
               <li>...</li>
               <li>...</li>
           </ul>
       </div>
   </div>
</nav>

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

Incorporating JavaScript Object-Oriented Programming in PHP

As someone new to JS programming, I am tasked with developing a php web application that relies on ajax calls for all actions without reloading the page. While I have completed the php and JS code, I am struggling to understand what JS OOP entails. My coun ...

javascriptchange the format from <string, string[]> to <string, string>

In my code, I came across a JavaScript object that consists of key/value pairs. Each value in this object is an array of strings: var errors = { "Message": ["Error #1", "Error #2"], "Email": ["Error #3", "Error #4"] }; My goal is to transform thi ...

Browser does not support the Media Query

I'm completely puzzled by Media Queries. I've been attempting to resolve this issue but cannot seem to identify where the problem lies. While creating a website with Wordpress, my header.php contains the following line: <meta name="viewpo ...

I am looking to transform my string code into a PDF file using an ASP.NET MVC controller by passing the string through an AJAX call to the controller

Currently, I am attempting to change an HTML string into a PDF format using iron PDF within the asp.net-mvc environment. However, since it is only a trial version, could you provide me with an alternative solution to converting an HTML string to a PDF in ...

Transferring an image file from PHP to JavaScript

I have encountered an issue with transferring images stored as LONGBLOB files in my database to a JS file for dimension comparison with the screen. Here is how I retrieve the images: function fillArrays(){ $idArray = array(); $sql = "SELECT oglas_id,s ...

Navigate to error page from AJAX request in ASP.NET MVC

If an error is returned from an AJAX call in a MVC application, how can you redirect to the error page Error.cshtml located in the Shared folder? $.ajax({ //Some stuff here... error: function (jqXHR, textStatus, errorThrown) { window.loc ...

Implementing a distinct approach to adding margins to div boxes using

Hello, I've been experimenting with the developer tools in Google Chrome to add margins to my navigation bar. The goal is to create gaps between the boxes. Any assistance would be greatly appreciated! http://jsfiddle.net/3jp1d0fe/8/ CSS div.contain ...

Attaching a $UI element to a <div> tag with JQuery may result in unexpected errors and issues

Attempting to connect SagePayments card elements to the paymentDiv. Followed their sample project for guidance, but encountering issues with populating the elements when running the program with a custom Sandbox merchantID and merchantKey. Chrome's de ...

Finding the Perfect Placement for an Element in Relation to its Companion

Is there a way to achieve an effect similar to Position Relative in CSS using jQuery? I have developed a tooltip that I want to attach to various objects like textboxes, checkboxes, and other text elements. My code looks something like this: <input i ...

"Creating dynamic web apps with the powerful duo of Meteor and Zurb

Just starting out with programming and currently working on a new web application using Meteor and AngularJS. I would like to incorporate the elements/css from 'Zurb Foundation For Apps' into my project... I am familiar with including Bootstrap ...

Unable to align text in the middle of the header

Seeking help with my design flaws, I have created a fiddle to showcase the issues that arise when attempting to make it responsive. The main problem is that the HEADING IN CENTER text is not aligned properly in the center. If I remove the position attribut ...

Disabling hover effects in Chart.js: A step-by-step guide

Is there a way to disable hover effects, hover options, and hover links on a chart using chart.js? Here is the code I have for setting up a pie chart: HTML.. <div id="canvas-holder" style="width:90%;"> <canvas id="chart-area" /> </div ...

Place a div element directly into a specific cell within the table

How can I place the following div <div class="inner"> <p>The first paragraph</p> <p>The second paragraph</p> </div> into a specific cell within a table? I am open to using either plain JavaScript or jQuery, althou ...

The landscape orientation media query does not adhere to the specified maximum width

I am currently working on creating a mobile landscape design for a website specifically tailored for iPhone SE and iPhone 12. In the process, I encountered an issue that caught my attention: Within two different breakpoints, I made adjustments to the top ...

Is there a way for me to view the data transmitted by JQuery to php?

I have this piece of jQuery code. I am curious to see what PHP will output. How can I display that result? <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> </head> <script> $.ajax({ ...

What is the reason behind Chrome's automatic scrolling to ensure the clicked element is fully contained?

Recently, I have observed that when performing ajax page updates (specifically appends to a block, like in "Show more comments" scenarios) Chrome seems to automatically scroll in order to keep the clicked element in view. What is causing this behavior? Wh ...

td having no line breaks causing text to extend beyond the cell

I have a challenge with using the nowrap property on td elements to ensure proper formatting of my tables. In the first table, everything wraps nicely, but in the second table, the content in the first "td" exceeds its designated space due to length. How c ...

Selecting multiple items from a grid using the Ionic framework

I am looking to create a grid of category images in Ionic framework, where users can select multiple categories and send their values to the controller. However, I'm unsure about how to make this happen with Ionic framework. Below is the view I curre ...

Adding one class at a time, with each new class being added every second

My goal is to add classes one by one [test0 test1 test2] up to 10, with each class being added after one second. $('.rating-block').AddClass('test0 test1 test2 ... test10' ); I am experimenting with the following code, but I don' ...

Iterating through two classes in a Javascript loop

Hello, I'm facing a small obstacle that I'm hoping to overcome using JavaScript/jquery. Essentially, I have multiple div classes and I want to create a loop that adds a class to specific divs without manually assigning an id to each one. The goal ...