When you click outside of a div, the dropdown menu disappears, but the toggle button does not appear

After creating a responsive bootstrap menu and adding jQuery code to hide the dropdown div when clicking outside of the toggle bar, I encountered an issue. Despite closing the toggle bar by clicking outside of the div, the toggle bar does not display correctly afterwards - it continues to show the cross symbol.

<nav class="navbar navbar-default navbar-static-top" role="navigation">
    <div class="navbar-header">
        <button type="button" id="ChangeToggle" class="navbar-toggle dropbtn" data-toggle="collapse" data-target="#navbar-collapse-1">
            <div id="navbar-hamburger">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </div>
            <div id="navbar-close" class="hidden">
                <span class="glyphicon glyphicon-remove"></span>
            </div>
        </button>
        <a class="navbar-brand" href="#">Brand</a>
    </div>
</nav>

Jquery:

<script type="text/javascript">
    $(function() {
        $('#ChangeToggle').click(function() {
            $('#navbar-hamburger').toggleClass('hidden');
            $('#navbar-close').toggleClass('hidden');  
        });
     });
</script>
<script>
    $(document).on('click',function(){
        $('.collapse').collapse('hide');
        $('#navbar-hamburger').toggleClass('show');
        $('#navbar-close').toggleClass('hidden'); 
    })
</script>

Answer №1

Give this a shot.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>


<nav class="navbar navbar-default navbar-static-top" role="navigation">
        <div class="navbar-header">
            <button type="button" id="ChangeToggle" class="navbar-toggle dropbtn" data-toggle="collapse" data-target="#navbar-collapse-1">
                <div id="navbar-hamburger">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </div>
                <div id="navbar-close" class="hidden">
                  <span class="glyphicon glyphicon-remove"></span>
                </div>
            </button>
          <a class="navbar-brand" href="#">Brand</a>
        </div>
        </nav>
</body>

</html>

 <script type="text/javascript">
        $(function() {
          $('#ChangeToggle').click(function() {
            $('#navbar-hamburger').toggleClass('hidden');
            $('#navbar-close').toggleClass('hidden');  
          });
        });
    </script>
    <script>

        $(document).on("click", function(event){
        var $trigger = $(".navbar");
        if($trigger !== event.target && !$trigger.has(event.target).length){
            $('.collapse').collapse('hide');
        $('#navbar-close').addClass('hidden');
        $('#navbar-hamburger').removeClass('hidden');
        }            
    });
    </script>

Let's address the problem at hand. You seem to be triggering on the entire document, which includes the navbar. This is causing your navbar to toggle as well. Try collapsing the navbar and toggling the button only when you click outside the navbar (excluding the navbar element)

Answer №2

Upon clicking the hamburger icon, the 'hidden' class is toggled.

$('#navbar-hamburger').toggleClass('hidden')

However, when you click anywhere else on the document, the 'show' class is toggled.

$('#navbar-hamburger').toggleClass('show')

This seems contradictory. It would be more logical to toggle the same class consistently.

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

"Encountering a puzzling issue with Django Rest Framework where the path setup is functioning for one link but not for

I'm currently attempting to connect to my MySQL database using the Django REST backend. On my frontend, I'm using Vue with Axios. Specifically, I have a junction table called TeacherSubjectJunction, and I want to access it through the following p ...

Creating a Thrilling Triple Image Transformation on Hover using Material-UI

Here is a Codepen showcasing a triple hover effect on an image: Codepen I attempted to recreate this effect as a styled component in React Typescript using MUI and MUI Image, but encountered an error with my styling that is preventing it from working in m ...

Using JavaScript to cheat on a typing test by automating the typing of letters

I am currently working on a solution to simulate key presses for a typing test. My idea is to extract individual letters from the text, store them in an array, and then simulate pressing each key with a delay between each press. Below is the HTML layout o ...

Is there a way to extract a data URL from an enlarged 2D context?

My canvas has a dynamic height and width based on the viewport width. I am using this canvas to create a final PNG image using toDataURL. However, I need the final PNG image to be at a fixed resolution. To achieve this, I have to scale up the 2D context fr ...

ExternalInterface.call in as3 leading to crashes in web browsers

I have a webpage with HTML and JavaScript that successfully hides and displays a flash movie object. However, I encounter a problem when trying to exit from the tab - the browser crashes without any error message. Can anyone provide assistance? Thank you. ...

The radio buttons in the HTML code are unresponsive to clicks (Note: The file extension is actually

I'm encountering a slight issue with what seems like an easier question: My angular object is structured as follows: $scope.questions = [ { questionText: "1. This is a test question#1", choices: [{ id: 1, text: "NO", ...

Foreign keys in a one-to-many relationship with Sequelize.js

I am in the process of developing a survey application using Node.js/Express and MySQL incorporating Sequelize.js ORM. However, I am encountering difficulties while establishing the relationship between the two models. My goal is to have the Questions&apo ...

How can I permanently eliminate an element or tag from the DOM using JavaScript or jQuery?

Having trouble removing empty H1 tags from my FE environment using JS. Despite removal, bots and crawlers can still view these tags in the Page Source and loaded DOM nodes. Is there a way to completely eliminate an element from the DOM? This is my html: ...

Can Array Values from Different Functions be Merged?

After running my code, you will notice that when a user inputs the quantity for a room, selects check-in and check-out dates, and clicks submit, two tables are displayed. The first table shows the room name, the entered quantity, and the price based on the ...

WP Highlighted Image

I'm facing a small issue where the featured image on my posts is not displaying in the desired size. I want the featured image to match the total width of the post, but it keeps showing up in its original size. I'm clueless about how to fix this ...

Searching for text on a webpage without an identifier using C#

How can I locate specific text on a webpage that is not designated with a specific ID or tag, but is simply plain text generated by an external source that I cannot control? I am using WatiN for automated testing and I need to find a way to click a button ...

What is the method for sending a status header without redirecting to a different page?

function verifyRegistration() { const xhr = new XMLHttpRequest(); xhr.open("GET", "http://ipaddressandport/users/register"); xhr.onload = () => { console.log("tes"); if (xhr.status === 400) { console.log ...

Immersive full-page backdrop image

My HTML page has a background image set through CSS: html{ margin-top:10px; background: url(xxxxx.jpg) no-repeat center center fixed; background-size: cover; } I am trying to change the background image dynamically from the Javascript side. ...

Creating a dashed circle in Three.js

I attempted to create a dashed circle following the pattern for dashed line, but unfortunately, the result was not as expected. Here is the code snippet I used: var dashMaterial = new THREE.LineDashedMaterial( { color: 0xee6666, dashSize: 0.5, gapSize: 0. ...

The Ajax request is failing to execute the callback function upon completion

While trying to upload an image using AJAX, I'm facing an issue where the success function is not being called upon completion. Within a form, there are two objects: <img class="b_logo" id="b_logo_img" src="images/no_image.gif"> <input cla ...

processes that are repeatedly called

<li class="cart_item clearfix" v-for="(product, index) in products" :key="index"> <div class="cart_item_text"><button type="button" class="btn btn-success" name=&q ...

Developing a structure with a condensed form of a category

Is it possible to create a Prisma schema for mongoDb that includes a condensed version of another object? For context, imagine the following sample data: const basicUser = { id: "62091d9ae17cad32fbe0eda5", displayName: "John Smith", }; const post ...

Using AJAX and jQuery to refresh a specific div when a specific button is clicked

I have a function that uses AJAX to update votes when clicked. Here is the code: $(function() { $(".vote").click(function() { var id = $(this).attr("id"); var name = $(this).attr("name"); var dat ...

The Ajax script is failing to retrieve search results

I am encountering an issue with my normal AJAX search functionality in which I need to retrieve data from a database when the form is submitted. The problem arises when trying to filter data between two specific dates using separate pages, it works fine bu ...

Looking for a way to prevent anonymous functions in jQuery using Greasemonkey?

Is there a way to prevent the execution of this particular jquery function? I've tried various scripts and even wrote my own, but nothing seems to work. $(document).ready(function () { $(window).on('beforeunload', function() { re ...