To close the responsive menu, simply click anywhere outside of the navigation bar

My issue involves a responsive menu with Bootstrap. On desktop, the menu closes fine; however, on the responsive view, I want it to close when clicking outside of the nav menu in any area. Here is my navigation code:

<!-- Navigation -->

<nav id="navigation-sticky" class="white-nav b-shadow">

    <!-- Navigation Inner -->

    <div class="nav-inner">

        <div class="logo">

            <!-- Navigation Logo Link -->

            <a href="#home" class="scroll">

                <!-- Your Logo -->

                <img src="" class="site_logo" alt=""/><br>

               </a>

        </div>

        <!-- Mobile Menu Button -->

        <a  class="mobile-nav-button colored"><i class="fa fa-bars"></i></a>

        <!-- Navigation Menu -->

        <div class="nav-menu clearfix ">

            <ul class="nav uppercase oswald">

                <li><a href="#home" class="scroll">home</a></li>

                <li class="dropdown-toggle nav-toggle" ><span href="#about" class="scroll">About App<b data-toggle="dropdown"></b></span>

                    <!-- DropDown Menu -->

                    <ul class="dropdown-menu uppercase gray-border clearfix">                       

                        <li><a href="#works" class="scroll">HOW DOES IT WORK?</a></li>
                        <li><a href="#features" class="scroll">Features</a></li>                        
                        <li><a href="#what-we-do" class="scroll">APP FLOW</a></li>
                        <li><a href="#faq" class="scroll">F.A.Q</a></li>

                    </ul>

                    <!-- End DropDown Menu -->

                </li>



                <li><a href="#portfolio" class="scroll">Service Types</a></li>

                <li><a href="#skills" class="scroll">Cities</a></li>

                <li><a href="#prices" class="scroll">Rates</a>

                </li>

                <li><a href="#download" class="scroll">Download</a></li>



                <li class="dropdown-toggle nav-toggle" ><span aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="dropdown-toggle scroll">Become a Driver</span>

                    <!-- DropDown Menu -->

                    <ul class="dropdown-menu uppercase gray-border clearfix">                       

                        <li><a href="#" class="scroll">Signup</a></li>
                        <li><a href="#" class="scroll">Flyer</a></li>                       


                    </ul>

                    <!-- End DropDown Menu -->

                </li>

                                    <li><a href="#" class="scroll">login</a></li>

                <li><a href="#contact" class="scroll">contact</a></li>

            </ul>

        </div><!-- End Navigation Menu -->

    </div><!-- End Navigation Inner -->

</nav><!-- End Navigation -->

Although the script I'm using successfully closes the menu, I'm encountering an issue where double-clicking is required instead of single-clicking to open the menu.

$('html').click(function() {
 $('#menu').hide(); 
});

Answer №1

Here is a possible solution for you:

$(document).mouseup(function (e)
{
    var container = $(".nav-menu");

    if (!container.is(e.target) // check if the click target is not the container
        && container.has(e.target).length === 0) // check if the click target is not a descendant of the container
    {
        container.css("display","none"); // hide the container
    }
}); 

Update: Give this a try instead

var container = $(".nav-inner div.nav-menu, .mobile-nav-button");

if (!container.is(e.target) // check if the click target is not the container...
    && container.has(e.target).length === 0) // ...or a descendant of the container
{
    $(".nav-inner div.nav-menu").slideUp(); // slide up the menu
}

Answer №2

Here is the solution you've been searching for:

$('body').click(function() {
//Hide the menu if it's visible
});

$('#menuwrapper').click(function(event){
    event.stopPropagation();
});

Answer №3

You can give this a shot:

$( "#menu" ).toggle( "slide" );

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

The Uglify task in Grunt/NPM is having trouble with this particular line of JavaScript code

Whenever I execute grunt build, Uglify encounters a problem at this point: yz = d3.range(n).map(function() { return k.map(x -> x[1]); }), An error message is displayed: Warning: Uglification failed. Unexpected token: operator (->). I have recentl ...

Utilize a singular object to contain multiple instances of the useState hook

const [regionData, setRegionData] = useState({ country: "", city: "", population: "", location: "", temp_min: "" }); Does anyone know a more efficient and cleaner way to replace these individual useState hooks by organizing them into ...

Transferring a zipped file from the backend of SailsJS to the frontend of React Redux via

My SailsJS Backend is responsible for generating a zip File when requested by my React App with Redux on the Frontend. I am utilizing Sagas for asynchronous calls and fetch to make the request. In the backend, I have attempted various methods such as: //z ...

I am looking to create an extension that can automatically paste text from a variety of lists, but unfortunately, I am struggling to get it up and running correctly

I'm having trouble pasting text into text boxes or documents. I've tried various methods, but nothing seems to work. Am I missing something? Is there a solution or could I get some assistance? manifest.json { "manifest_version": 3, ...

Error encountered during Jest snapshot testing: Attempting to destructure a non-iterable object which is invalid

I am currently facing an issue with my React codebase where I am attempting to create snapshot tests for a component. However, Jest is showing an error indicating that I am trying to destructure a non-iterable instance. Despite thoroughly reviewing the cod ...

Is Firebase the Answer to Shopify's Authentication Validation?

I've been following this tutorial on building a Shopify app using Node, Nextjs, and React. Progress has been smooth so far, but I've now reached a point where I need to store some of my app data in Firestore. My current approach involves utiliz ...

Is there an issue with retrieving data from asp.cs through ajax?

Currently, I am in the process of learning asp.net and trying to access server data to populate a textbox with the retrieved information. public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) ...

The native javascript modal fails to appear

I'm attempting to implement the functionality from this Codepen demo into my project. I've copied over the HTML, CSS, and JavaScript code: <!DOCTYPE HTML> <html> <head> <script> var dialog = docume ...

What is the best way to trigger the keyup event in that moment?

Currently, I am using regex to validate the name field. Each time a key is pressed, a validation function is triggered. If the input matches the regex pattern, I need to empty out that specific character from the input field. However, when previewing the p ...

"Troubleshooting: How to Fix Issues with document.getElementById on Dynamic Div

Struggling to incorporate div elements and generate graphs with Google charts? The issue arises in the draw function, where attempts to access a div element using document.getElementById() result in null values and an error message stating "container not ...

AngularJSError

I am completely new to AngularJS and I've been tasked with debugging someone else's code. While debugging in Google Chrome, I encountered the following error: TypeError: accountService.logIn(...).success is not a function. The issue lies with ...

Troubleshooting: Images not displaying properly in React due to Webpack configuration bottleneck,

I am facing an issue with loading images in my React application. Some images are set up in the CSS file like this: background-image: url('/../img/logo.png'); On the other hand, I would like to use images inside React components using the img ...

Continuous polling with Ajax in Rails does not trigger the display of an alert box

Trying to implement ajax polling using the RailsCast tutorial on ajax polling (#229) but encountering an issue where the alert box doesn't pop up after running the server. Here's the code in app/views/quotes/index.js.erb: alert('Hey') ...

What is the best way to display a scrollbar at the bottom of the table while setting the table height to

After writing the css provided below, I noticed that it works fine on my laptop screen. However, when viewing it on a larger monitor, there is empty space at the end of the table. .wrapper{ width:auto; height: 500px; overflow-x: scroll; ...

What is the best way to access a custom object in JavaScript that was created in a different function?

Currently working with JavaScript and jQuery technology. In one of my functions that runs on document ready, I am creating objects with different attributes. While I can easily access these object attributes within the same function, I'm facing diff ...

"Troubleshooting: My PHP script is not displaying CKEditor content stored in the database as HTML –

As I work on the blog section of a project, I encountered an issue with displaying HTML content saved from CKEditor in PHP. Instead of rendering the HTML tags, it shows plain text. I have attempted various solutions but haven't been able to fix the pr ...

Strategies for resolving the error "Cast to ObjectId failed for value"

<form action="" method="post"> <input type="password" name="password" placeholder="Type Your Password Here" required> <input type="hidden" name="user_id" value=&q ...

The process of embedding variables within a JSON Array function in JavaScript

As a newcomer to JavaScript, I am facing an issue while trying to create a simple program. I am attempting to store the variables 'name', 'document', and 'code' inside the JSON array called 'records'. var records = ...

An error was encountered: "Uncaught SyntaxError: Unable to utilize import statement outside of a module in

I have come across the following code while learning React and trying to execute it. HTML <html> <head> <link href="index.css" rel="stylesheet"> </head> <body> <div id="r ...

Refreshing Angular Page

I'm looking for a way to reset my Angular page back to its original state with just one button click. I attempted to use the angular.copy method, but encountered an error. I have various scope and controller variables that I don't want to reset i ...