I am struggling to figure out how to make the responsive menu close

#switch image
var up = 'https://image.flaticon.com/icons/svg/149/149187.svg';
var down = 'https://image.flaticon.com/icons/svg/128/128397.svg';

$('#resNavToggle').click(function() {
  if ($('.resNavIcon').attr('src') === up) {
    $('.resNavIcon').attr('src', down);
  } else {
    $('.resNavIcon').attr('src', up)
  }
})


//toggle sub-menu
$(document).ready(function(){
    $("img.resNavIcon").click(function(){
        $("ul.resNav").toggle();
 
    });


    $("li.serviceLink").click(function(){
        $("ul.serviceNav").show();
        $("ul.resNav").hide();
    });


    $("li.serviceNavClose").click(function(){
        $("ul.serviceNav").hide();
        $("ul.resNav").show();
    });
});
.resNav       { display:none}
.serviceNav      { display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://image.flaticon.com/icons/svg/149/149187.svg" width="40" height="25"   class="resNavIcon"  id="resNavToggle">


<ul class="resNav">
<li><a href="">Main-menu</a></li>
<li class="serviceLink">Sub-menu ></li>
<li><a href="">Main-menu</a></li>
<li><a href="">Main-menu</a></li>
<li><a href="">Main-menu</a></li>
</ul>


<ul class="serviceNav">
<li class="serviceNavClose">< Main-menu</li>
<li><a href="">Sub-menu</a></li>
<li><a href="">Sub-menu</a></li>
<li><a href="">Sub-menu</a></li>

</ul>

If you're looking for a solution to a responsive menu issue, check out this simple two-tier responsive menu I've created: https://jsfiddle.net/wmxujcy4/2/

I managed to implement the image toggle functionality and the sub-menus as needed after following some tutorials. However, there seems to be an issue when attempting to collapse both menus by clicking the main 'close' icon while on a 'sub-menu'.

//switch image
var up = 'https://image.flaticon.com/icons/svg/149/149187.svg';
var down = 'https://image.flaticon.com/icons/svg/128/128397.svg';

$('#resNavToggle').click(function() {
  if ($('.resNavIcon').attr('src') === up) {
    $('.resNavIcon').attr('src', down);
  } else {
    $('.resNavIcon').attr('src', up)
  }
})

//toggle sub-menu
$(document).ready(function(){
    $("img.resNavIcon").click(function(){
        $("ul.resNav").toggle();

    });

    $("li.serviceLink").click(function(){
        $("ul.serviceNav").show();
                $("ul.resNav").hide();
    });

    $("li.serviceNavClose").click(function(){
        $("ul.serviceNav").hide();
                    $("ul.resNav").show();
    });
});

Currently, both menus get stuck and the incorrect icon is displayed instead of collapsing both menus. Any assistance in resolving this issue would be greatly appreciated.

Answer №1

You can easily determine if the sub-menu is currently visible. If it is, simply hide both ul.

//toggle image
var plus = 'https://image.flaticon.com/icons/svg/149/149187.svg';
var minus = 'https://image.flaticon.com/icons/svg/128/128397.svg';

$('#resNavToggle').click(function() {
  if ($('.resNavIcon').attr('src') === plus) {
    $('.resNavIcon').attr('src', minus);
  } else {
    $('.resNavIcon').attr('src', plus)
  }
});


//open and close sub menu
$(document).ready(function() {
  $("img.resNavIcon").click(function() {
    if ($("ul.serviceNav").is(":visible")) {
      $("ul.resNav").hide();
      $("ul.serviceNav").hide();
    } else {
      $("ul.resNav").toggle();
    }
  });

  $("li.serviceLink").click(function() {
    $("ul.serviceNav").show();
    $("ul.resNav").hide();
  });

  $("li.serviceNavClose").click(function() {
    $("ul.serviceNav").hide();
    $("ul.resNav").show();
  });
});
.resNav {
  display: none
}

.serviceNav {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://image.flaticon.com/icons/svg/149/149187.svg" width="40" height="25" class="resNavIcon" id="resNavToggle">



<!-- Res Nav -->
<ul class="resNav">
  <li><a href="">Main-menu</a></li>
  <li class="serviceLink">Sub-menu &gt;</li>
  <li><a href="">Main-menu</a></li>
  <li><a href="">Main-menu</a></li>
  <li><a href="">Main-menu</a></li>
</ul>


<ul class="serviceNav">
  <li class="serviceNavClose">&lt; Main-menu</li>
  <li><a href="">Sub-menu</a></li>
  <li><a href="">Sub-menu</a></li>
  <li><a href="">Sub-menu</a></li>
</ul>

Answer №2

To determine the visibility of the sub menu, you can choose to hide it if it's currently visible or toggle its display status.

$("img.resNavIcon").click(function(){
        if($("ul.serviceNav").is(":visible")){
            $("ul.serviceNav").hide();
      }else{
        $("ul.resNav").toggle();
      }

    });

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

What is the purpose of including window and undefined as parameters in this jQuery plugin?

Exploring the jquery resize plugin has left me puzzled about its inner workings: Typically, we only pass a jQuery object into jquery plugins like this: (function($){ ....plugin code.... })(jQuery); However, in the "resize" plugin, both window and un ...

Replace HTML elements with AJAX and JavaScript

Working with MySQL data in pyramid presents a challenge as I need to dynamically change an HTML if statement based on the results from JS ajax calls. The main page receives data from views.py and passes it to the .mak script. The key views here are the ma ...

After clicking, revert back to the starting position

Hey there, I have a question about manipulating elements in the DOM. Here's the scenario: when I click a button, a div is displayed. After 2 seconds, this div is replaced by another one which has a function attached to it that removes the div again. ...

Dealing with errors in multer and express-validator aspects

Is there a way to validate a form that includes an image using multer and other fields with express-validator? I keep encountering an undefined error (req.validationError) in the post route. Any suggestions on how to resolve this issue? server.js const e ...

Understanding how to accurately pair specific data points with their corresponding time intervals on a chart

I'm currently working with apexcharts and facing an issue with timestamps. I have data for sender and receiver, each having their own timestamps. The x-axis of the graph is based on these timestamps, but I am struggling to map the timestamp with its r ...

The hot loader is replicating code multiple times instead of conducting hot swapping

Every time I make a change in a component, webpack recompiles and React hot swaps the module over. However, I've noticed that my code runs multiple times after each hot module swapping occurrence. For example, if I make a change once, the functions ru ...

Configuring Next-auth CredentialProvider and setting up redirection

I'm feeling a bit lost when it comes to understanding how the credentials provider and redirects work. The documentation mentions that the credentials provider doesn't support a callback and is specifically for OAuth providers, which I understand ...

AngularJS - utilizing the directive $parsing to evaluate an expression and bind it to the scope object

I have set up my isolated directive to receive a string using the @ scope configuration. My goal is to convert this string into an object on the scope, so that I can manipulate its properties and values. Here's how it looks in HTML: <div directiv ...

Steps for transferring a checked statement from an HTML document to a JavaScript file

Struggling to transfer checked statements from HTML to JS file {{#each readValues }} <br> Plug: {{@index}} => {{this}} <input type='checkbox' class="plug" onclick="sendData();" /> {{/each}} The code above is written i ...

Using react-hook-form for form submission and managing state in React

I want a button that toggles between displaying "Edit" for entering Edit mode and "Save" for submitting the form. However, the issue is that when I press the button while it shows "Edit," it submits the form. Link to codesandbox with the code provided be ...

While executing a jssor code in SP 2007, IE experiences freezing issues

I've integrated a jssor slider with vertical navigation (without jQuery) into a Sharepoint 2007 page using CEWP. All the image links have been replaced with images stored in the SP image library, and the jssor.slider.min.js file has been uploaded to t ...

Changing the li tag by clicking on it is a simple task that can be easily

Whenever I click on a tag, I want the li class to change to "active" and open a new page with the corresponding tag as active. For example, if I click on the Overview tag, the new page should open with the li tag as active. I have attempted to write some c ...

Unable to delete product from shopping cart within React Redux reducer

Currently, I am tackling the challenge of fixing a bug in the shopping cart feature of an e-commerce website I'm working on. The issue lies with the remove functionality not functioning as expected. Within the state, there are cartItems that can be ad ...

Tips for arranging div elements in a grid-like matrix layout

I am facing a challenge in arranging multiple rectangular divs into a grid structure with 10 columns and 10 rows. The CSS styles for the top, bottom, left, or right positions must be in percentages to accommodate zoom in and out functionality without overl ...

Make changes to external CSS using HTML and JavaScript

Is it possible to dynamically change the value of a background in an external CSS file using JavaScript? Currently, all my pages are connected to a CSS file that controls the background for each page. I am attempting to modify the background by clicking a ...

Utilizing Vue.js transitions to display content with a one-time transition limit

I have followed the Vue.js documentation given below to implement the show transition, but I'm struggling with stopping the hide effect on the second click. Is there a way to achieve this? https://v2.vuejs.org/v2/guide/transitions.html#a Can I conti ...

Enhanced JavaScript Regex for date and time matching with specific keywords, focusing on identifying days with missing first digit

I have a specific regular expression that I am using: https://regex101.com/r/fBq3Es/1 (audiência|sessão virtual)(?:.(?!audiência|sessão virtual|até))*([1-2][0-9]|3[0-1]|0?[1-9])\s*de\s*([^\s]+)\s*de\s*((19|20)?\d\d) ...

Accessing Elements by Class Name

I've been searching for information on the capabilities of getElementsByClassName for hours. While some sources mention it returns an HTML collection of items, length, and named items, w3schools provides an example where innerHTML is utilized: var x ...

Troubles encountered with example code: Nested class in an exported class - Integrating Auth0 with React and Node.js

I am currently attempting to execute tutorial code in order to create an authentication server within my React project. Below is the code snippet provided for me to run: // src/Auth/Auth.js const auth0 = require('auth0-js'); class Auth { co ...

Switching between two states of a single 'td' element within a column

I am trying to implement a feature where only specific elements in the fourth column of a four-column table toggle when clicked. For example, clicking on an element in the fifth row third column should toggle the corresponding element in the fifth row four ...