jQuery Animation: Creative Menu Icon Display

Whenever the toggle menu's navigation icon is clicked, it triggers an animation that transforms the "hamburger" icon into an "X", causing the navigation menu to drop down.

If a user clicks either the navigation icon or outside of the active toggle menu (when the menu has dropped down), the "X" icon will revert back to the "hamburger" icon.

The issue I'm currently facing is that even if the toggle menu is not active (meaning the menu hasn't dropped down) and the user clicks outside the navbar anywhere on the page, the navigation icon's animation is still activated.

I would appreciate any assistance in resolving this matter :-)!

CSS:


/*global styles*/
.body {
width: 100%;
margin: 0;
list-style: none;
text-decoration: none;
}
.header {
background: #d3d3d3;
width: 100%;
position: fixed;
top: 0;
left: 0;
} 
.nav {
position: fixed; 
width: 100%; 
text-align: center; 
display: none; 
background-color: #d3d3d3; 
left: 0;
} 
.nav > li { display: block; border-bottom: 0.05em solid #000000; } 
.nav > li:last-child { border-bottom: none;
}

jQuery:


/*navigation icon animation*/
jQuery(document).ready(function() {
$('#toggle-menu').click(function(){
$(this).toggleClass('menu-is-active');
});

/* click outside of nav to trigger navigation icon animation */
$(document).click(function() { $("#toggle-menu").toggleClass(); });         $("nav").click(function(e) { e.stopPropagation(); return false; });

/*----/----navigation icon animation*/

/*toggle menu*/
jQuery("#toggle-menu").click(function() {
jQuery(".nav").slideToggle();
});
/* click outside of nav to close toggle*/ $(document).click(function() { $(".nav").hide(); }); $("#toggle-        menu").click(function(e) { e.stopPropagation(); return false; });
/*----/----toggle menu*/

});

html:

<div class="header">
<div class="navbar">

<a href="" class="logo" style="display: inline-block;">LogoPlaceHolder</a>

<a id="toggle-menu">
<div>
<span class="top"></span>
<span class="middle"></span>
<span class="bottom"></span>
</div>
</a>

</div>
</div>


<ul class="nav">
    <li><a href="" style="display: inline-block; width:100%;">Home</a>        </li>
    <li><a href="" style="display: inline-block; width:100%;">About</a></li>
    <li><a href="" style="display: inline-block; width:100%;">News</a></li>
    <li><a href="" style="display: inline-block; width:100%;">Contact</a></li>
</ul>

Answer №1

After some testing, I discovered that the strange behavior only occurs when first toggling a class by clicking on the "hamburger" icon and then closing it by clicking elsewhere on the document. However, if I close the menu by clicking on the "X" button, everything functions correctly for me. Interestingly, toggling the class on document click will still trigger even if it wasn't explicitly specified.

I decided to try using removeClass() instead of toggleClass() on the document click event, and surprisingly it resolved the issue entirely.

Answer №2

Here is a simple solution:

/animation for navigation icon/

var clickTrigger='X';

jQuery(document).ready(function () {
    $('#toggle-menu').click(function () {
        clickTrigger='X';
        $(this).toggleClass('menu-is-active')

    });

    /* clicking outside the nav triggers the navigation icon animation */
    $(document).click(function () {


        if (clickTrigger=='X')
        {
          $("#toggle-menu").toggleClass();
          clickTrigger='ham';
        }



    });
    $("nav").click(function (e) {
        e.stopPropagation();
        return false;
    });

    /*----/----animation for navigation icon*/

    /*toggle menu*/
    jQuery("#toggle-menu").click(function () {
        jQuery(".nav").slideToggle();
    });
    /* clicking outside of the nav will close the toggle*/
    $(document).click(function () {
        $(".nav").hide();
    });
    $("#toggle-menu").click(function (e) {
        e.stopPropagation();
        return false;
    });
    /*----/----toggle menu*/

});

Fiddle: https://jsfiddle.net/wexd3spp/14/

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

Accessing pseudo elements when their sibling is hovered can be achieved by using CSS selectors and combinators

I am struggling with the following html code: <div class="content"> <h2><a href="#">Hero</a></h2> <h2>Hero</h2> <div class ="tricky"></div> </div> The "co ...

Is it possible to compare escaped data with the unescaped value of a select box in JavaScript?

On my webpage, I have a functionality that involves fetching select box options through an AJAX request. I then create the select box based on this data, and later use the selected option to retrieve additional information from the response received via AJ ...

Having difficulty in replicating and obtaining flash video content from a website through HTML coding

I'm having trouble downloading a flash video, as traditional download software isn't working. I attempted to directly access the video from the html script itself, following this tutorial : https://www.youtube.com/watch?v=waE3J0Jej_0 The script ...

How important is a neglected parameter in the world of JavaScript?

Curious about the value of an ignored parameter in JS? Imagine a function that requires 2 values as parameters, but you only provide one during the call. What happens to the other parameter? You might think it's undefined, but the code below only show ...

CodePen experiencing issues with JS/jQuery coding functionality

Experimenting on CodePen, I am practicing using JS and jQuery with HTML. HTML: <button>asdasads</button> JS: $('button').on('click', function() { alert('woot'); }); Visit this pen, unfortunately it's ...

Step-by-step guide to dynamically updating array indexes using jQuery and HTML input fields

const list = []; function updateIndex(index) { list.splice(index, 1); console.log(list); var html = ""; html += "<ul id = 'del'>"; for (var i = 0; i < list.length; i++) { html += "<li>" + list[i] + " <button oncl ...

An error arises when using the command window.close()

I have encountered an issue with this code where it closes all Safari windows but works fine in Internet Explorer. What should I do? Is there an alternative method for closing the current opened window in every browser? <input type='button' v ...

Utilize Angular 5 to implement URL routing by clicking a button, while also preserving the querystring parameters within the URL

I have a link that looks like this http://localhost:4200/cr/hearings?UserID=61644&AppID=15&AppGroupID=118&SelectedCaseID=13585783&SelectedRoleID=0 The router module is set up to display content based on the above URL structure { path: & ...

Pulling out a particular row from an HTML table with the help of HTML::TreeBuilder

I am a beginner in perl programming and I am facing a major challenge. I need to parse an HTML file that contains a single table, and extract a specific row based on one of its column entries. Here is a snippet of the HTML file: many previous rows descri ...

The specified container is not a valid DOM element

Recently, I decided to implement Redux into my React application. However, as I began setting everything up within my index.js file, I encountered an error message: https://i.sstatic.net/4kL2T.png. After some research, I learned that this error is related ...

Creating a function within a module that takes in a relative file path in NodeJs

Currently, I am working on creating a function similar to NodeJS require. With this function, you can call require("./your-file") and the file ./your-file will be understood as a sibling of the calling module, eliminating the need to specify the full path. ...

The JavaScript popup is not functioning properly when using a comparison operator

There are 5 links with mini preview photos and URLs. Out of the 3 links, two are considered good while the other two are not. Clicking on a good link takes me to a new page, but clicking on an error link changes the href attribute to addressError, triggeri ...

What could be the issue with my JSON data stream?

Trying to set up the Fullcalendar JQuery plugin with a JSON feed has been a bit of a challenge. The example provided with the plugin works perfectly, so it seems like there might be an issue with my own feed. Here is the output from the working example JS ...

Specify the content type header in IE request with AJAX

Is it feasible to specify the http content-type request header as 'application/json' while sending a cross domain jquery ajax http request from Internet Explorer? We are attempting to access a REST WCF service that relies on the content type pro ...

.Certain IDs on a website may not respond to clicks due to various reasons

I have created a JavaScript file to automatically click a button on a website using a Chrome extension. When testing the code using Chrome Script snippet, I noticed that it worked for some IDs but not for others. Can someone please help me with this issue? ...

What are the best scenarios for employing Server Side Includes?

The documentation for Apache regarding SSI mentions that it is a convenient method to incorporate small snippets of information, like the current time. However, if most of your webpage content is being dynamically generated when served, then it suggests ...

HTML - No alterations to Writing Mode

Hello everyone, I'm attempting to display a header vertically in my table but the writing-mode property is not having any effect. CSS .VerticalText { writing-mode: tb-rl; } HTML <td rowspan="6" id="tableHeader" class="Border"> <h1 cl ...

Requesting the user to repeatedly input their birth year until it is less than the current year

Can anyone help me figure out how to display a prompt until the user enters a birth year that is less than the current year? I've tried using a loop in my code, but I'm having trouble getting it right. Any assistance would be greatly appreciated. ...

Running a JavaScript file from Docker to fill a MongoDB database is not working when using the WSL shell on Windows 10

I'm facing some issues while trying to populate my MongoDB using a script. Every time I run the script, I encounter errors even though the Docker container is up and running. For reference, I'm on Windows 10 using WSL shell. https://i.stack.img ...

Step-by-step instructions for creating a shadow page and displaying a loading div when an ajax call is made

Is it possible to shadow the entire page when a user clicks a button, display a div in the center of the page with a loading gif, and then make an ajax request to a page? If so, can someone explain how to achieve this? I found here, the following code: ( ...