Ways to add a dynamic collapse feature to my menu, triggered by clicking outside the button

Here is my navbar:

http://jsfiddle.net/Hg4Ts/3/

This is the html code for my navbar:

<div class="wrapper">
    <div class="navbar navbar-default" role="navigation">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Project name</a>
        </div>
        <div class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
              <ul class="dropdown-menu">
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li class="divider"></li>
                <li class="dropdown-header">Nav header</li>
                <li><a href="#">Separated link</a></li>
                <li><a href="#">One more separated link</a></li>
              </ul>
            </li>
          </ul>
          <ul class="nav navbar-nav navbar-right">
            <li class="active"><a href="./">Default</a></li>
            <li><a href="../navbar-static-top/">Static top</a></li>
            <li><a href="../navbar-fixed-top/">Fixed top</a></li>
          </ul>
        </div><!--/.nav-collapse -->
    </div>
</div>

This is the javascript code I am using:

$(document).ready(function () {
    function CloseNav() {
        $(".navbar-collapse").stop().css({ 'height': '1px' }).removeClass('in').addClass("collapse");
        $(".navbar-toggle").stop().removeClass('collapsed');
    }

    $('html').click(function (event) {
        var clickover = $(event.target);
        var _opened = $(".navbar-collapse").hasClass("navbar-collapse in");
        if (_opened === true && !clickover.hasClass("navbar-toggle")) {
            CloseNav();
        }

    });
});

I want to add an animated collapse effect to my menu when clicked outside the button. Also, how can I make the menu button change color only when the collapse is open?

Answer №1

Try out this revised solution that may better suit your needs. Modify your CloseNav() function as shown below:

function CloseNav() {
    $(".navbar-collapse").stop().animate({'height': 0},300, function () {
        $('.navbar-collapse').removeClass('in').addClass("collapse");
    });
    $(".navbar-toggle").stop().removeClass('collapsed');
};

By incorporating the .collapse class to the navigation bar after the animation, you can achieve the desired slide up effect instead of an instant height switch.

Check out this demo on JSFiddle

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

Mixing up bootstrap grid columns with mobile-responsive view patterns

I have this specific design that I need help with: This design is intended for desktop or larger screens only. Note: The red and green boxes in the design are not of equal height. https://i.sstatic.net/snAKt.png For mobile devices or smaller screens, t ...

Regular expression looking for a single letter followed by a space, and then one or more digits

I attempted the following patterns: /[A-Za-z]++[ ]*+[1-9]/ and: /^[\D*]+[\s]+[\d]/ However, they are not producing the desired results. Any suggestions? ...

Creating with NodeJS

I'm encountering an issue where my code is not waiting for a response when trying to retrieve data from a database. The connection is fine and everything works well, but Express isn't patient enough for the data to come through. Despite trying v ...

Implement unique calculations for each input type of 'number' using JQuery

Currently, I am working on PHP code combined with JQuery for calculations. My experience with JQuery is not extensive, so I will explain using this image: https://i.sstatic.net/bt5Uq.png I have three fields: "capital", "markup", and "Cost Per Item". Each ...

When an image is clicked, I am interested in loading HTML content

I am trying to implement a feature where a local HTML page can be loaded within a div to replace an existing one without the entire page having to reload. An example of what I want to achieve can be seen at . When you click on the game image, the player i ...

The CSS3 selector matching a value starting with "[attribute^=value]" does not match a value that has spaces after the quotation marks

When using the div[class^="test"] selector, keep in mind that it will not select an element with a class attribute like class=" test-something" (This selector was generated on the backend.) Using the div[class^=" test"] is not a valid choice. ...

Sluggish Performance of Material UI Table

Hey there! I've been working with Material-UI for a large data table, but I've noticed it's quite slow. Before reaching out on Github, I wanted to see if other users have any tips or workarounds to help improve performance. Here is the code ...

Access one React application within another React application on the same webpage

Currently, I've structured the front-end of my website as micro-services – each functional section is a react-habitat application bundled with CSS and HTML for reusability. While this approach has proven effective for most parts of the site, I' ...

Display a caution when verifying a function's value instead of its return value

I've encountered a common pitfall (especially with autocomplete) while testing a function return value. There are instances when I forget to include the parentheses () at the end, causing it to always return true. class Foo { public bar(): boolea ...

Utilizing PHP to dynamically generate href links based on radio button selection in real-time interaction with JavaScript

Currently, I am utilizing the MVC framework within Codeigniter and I have a view that contains a link. It's important to mention that the href value is generated by calling a PHP function which takes 'auth/mylogin' as a parameter: <a hre ...

Showing Local Website Content on iOS in React Native: A Step-by-Step Guide

Struggling to Display Local Web Code on iOS with React Native I've attempted various solutions but haven't had success. ...

Tips for sending a div value that is not included in the model to the backend controller action

Question: I am looking to have a single div element in the user interface that can display a value added via JQuery and then be accessible in the backend once the form is submitted. View: @model ScheduleAptMV using (Html.BeginForm()) ...

The horizontal alignment of a jQuery div is off-center

There is a div element with a width: 50% and some text inside. Using jQuery, I am calculating the widths of both. Then, I attempted to horizontally center the text within the div using this jQuery code: var wrapperWidth = $("#wrapper").width(); var textW ...

The function screen.getByText is not available in this context

My experience with jest and react-testing-library has been smooth for the most part, but I encountered some challenges when transitioning to the screen > getByText/etc testing method. Test describe('test the dashboard when loaded', () => { ...

Best method for distributing components across nextjs zones?

Scenario: I am currently working on a project using Next.js and taking advantage of its multi zones feature. This feature allows us to run multiple independent NextJS applications as a unified app, managed by different teams. The Issue: One challenge I fa ...

Adding default parameters in AngularJS Route-UI is a useful feature for setting up

Using angular UI-Router in my app, I've set up my base language as English. I have both English and Hebrew locals, and I want to avoid adding parameters to the URL if the language is English. For instance: Home English --> http://example.com/ ...

Adjusting Mat Expansion Indicator Rotation

After successfully moving the mat Indicator to the left and using the transform attribute to make it turn inward when expanding, I now want to style it so that the indicator faces upward when expanded and downward when collapsed. How can I achieve this uni ...

Generating an Audio element on the fly using Javascript

I am looking to dynamically generate an audio tag within the <div class="audio-player" id="song"></div> section. I require: <audio id="audio-player" controls="controls" src="media/Blue Browne.mp3" type="audio/mpeg"> to be placed insid ...

Error message: "Unassigned value in knockout.js"

Here is my code snippet for binding to a textbox: var CategoryViewModel = { categoryModel: ko.observable({ categoryId: ko.observable(), categoryName: ko.observable(), active: ko.observable() }), GetCategoryById: functio ...

AngularJS enables the creation of multiselectable dropdown checkboxes

I am looking to create a dropdown list of checkboxes that allows for multiple selections. I have attempted to implement the code below, but I am facing an issue where the template refreshes each time a checkbox is clicked, preventing me from making multi ...