Hide the mobile menu after an option is clicked

I managed to implement a mobile menu on my single-page website by utilizing code I found online. Currently, the menu only opens or closes when the main navigation bar is selected due to the JavaScript I have integrated. Is it feasible for the menu to automatically close once a menu item is chosen? This way, when a menu option is clicked, and the page scrolls to an anchor point, the navigation menu will also close instead of remaining open.

For reference, here's a snapshot of my existing menu: https://jsfiddle.net/kmracozg/

HTML:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript" ></script>
</head>

<a id="touch-menu" class="mobile-menu" href="#"><div class="mobile-logo">LOGO HERE</div><div class="mobile-menu-dropdown">MENU</div></a>
<div class="header-logo">LOGO HERE</div>
    <nav>
    <ul class="menu">
   <li><a href="#"></i>HOME</a>
   <li><a href="#"></i>ABOUT</a>
   <li><a href="#"></i>SOLUTIONS</a>
   <li><a href="#"></i>WORK</a>
   <li><a href="#"></i>CONTACT</a>
   <li><a href="#"></i><b>CLIENT AREA</b></a>
  </ul>
  </nav>

CSS:

/* ---------- Google Font ---------- */
@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,400italic,600,700,800);

/* RESET STYLES */
*, html, body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, label, fieldset, input, p, blockquote, th, td { margin:0; padding:0 }


body{background:#000;
font: 14px "Open Sans", Helvetica, Arial, sans-serif;
width:100%;}

<!-- More CSS Code Snippet Here -->

.menu ul ul {left: 149px;
top: 0px;
}

.mobile-menu{display:none;
width:100%;
padding:16px;
background:#ffffff;
color:#393939;
text-transform:uppercase;
font-weight:600;
}
.mobile-menu:hover{background:#ffffff;
color:#393939;
text-decoration:none;
}

<!-- Rest of the CSS Code Snippet Here -->

@media (max-width: 900px) {

<!-- Media Queries CSS Code Here -->
              
});

Javascript:

$(document).ready(function(){ 
var touch = $('#touch-menu');
var menu = $('.menu');

$(touch).on('click', function(e) {
e.preventDefault();
menu.slideToggle();
});

$(window).resize(function(){
var w = $(window).width();
if(w > 900 && menu.is(':hidden')) {
menu.removeAttr('style');
}
});

});

Answer №1

To show the menu again, you need to link an event to the li a

$(document).ready(function(){ 
var touch = $('#touch-menu');
var menu = $('.menu');

$(touch).on('click', function(e) {
e.preventDefault();
menu.slideToggle();
});
    $("ul.menu").find("li a").click(function() {
        if(menu.hasClass('mobile')) menu.slideToggle();
    });

$(window).resize(function(){
        var w = $(window).width();
        if(w > 900) {
            menu.removeAttr('style');
            menu.removeClass('mobile');
        } else {
            menu.addClass('mobile');
        }
    });
     
  // initial setup for setting the class name
     var w = $(window).width();
     if(w > 900) {
            menu.removeAttr('style');
            menu.removeClass('mobile');
        } else {
            menu.addClass('mobile');
        }
    
});
/* ---------- Google Font ---------- */
@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,400italic,600,700,800);

/* RESET STYLES */
*, html, body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, label, fieldset, input, p, blockquote, th, td { margin:0; padding:0 }


body{background:#000;
font: 14px "Open Sans", Helvetica, Arial, sans-serif;
width:100%;}




nav{display:block;
background:#ffffff;
text-align: right;
}

.menu{display:block;}

.menu li{display: inline-block;
position: relative;
z-index:100;}

.menu li:first-child{margin-left:0;}

.menu li a {font-weight:600;
text-decoration:none;
padding:40px 20px;
display:block;
color:#393939;

-webkit-transition: all 0.2s ease-in-out 0s;
   -moz-transition: all 0.2s ease-in-out 0s;
   -o-transition: all 0.2s ease-in-out 0s;
   -ms-transition: all 0.2s ease-in-out 0s;
   transition: all 0.2s ease-in-out 0s;
}

.menu li a:hover, .menu li:hover > a{color:#B11A25;
background:#e4e4e4;}

.menu ul {display: none;
margin: 0;
padding: 0;
width: 150px;
position: absolute;
top: 43px;
left: 0px;
background: #ffffff;
}

.menu ul li {display:block;
float: none;
background:none;
margin:0;
padding:0;
}
.menu ul li a {font-size:12px;
font-weight:normal;
display:block;
color:#797979;
border-left:3px solid #ffffff;
background:#ffffff;}

.menu ul li a:hover, .menu ul li:hover > a{
background:#f0f0f0;
border-left:3px solid #B11A25;
color:#797979;
}

.menu li:hover > ul{ display: block;}
.menu ul ul {left: 149px;
top: 0px;
}

.mobile-menu{display:none;
width:100%;
padding:16px;
background:#ffffff;
color:#393939;
text-transform:uppercase;
font-weight:600;
}
.mobile-menu:hover{background:#ffffff;
color:#393939;
text-decoration:none;
}

.mobile-menu img { display: block; margin: 0 auto; }

.mobile-menu-dropdown{ display: table; margin: 10px auto 0; }

.header-logo { position: absolute; padding: 30px; }

@media (max-width: 900px) {


.menu{display:none;}

.mobile-menu{display:block;}

nav{margin:0;
background:none;}

.menu li{display:block;
margin:0;}

.menu li a {background:#ffffff;
color:#797979;
border-top:1px solid #e0e0e0;
border-left:3px solid #ffffff;
padding:20px;
}

.menu li a:hover, .menu li:hover > a{
background:#e4e4e4;
color:#B11A25;
border-left:3px solid #B11A25;}

.menu ul {display:block;
position:relative;
top:0;
left:0;
width:100%;}

.menu ul ul {left:0;}

.header-logo { display: none; }

.mobile-logo { text-align: center; }

nav { text-align: left !important; }
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript" ></script>
</head>

<a id="touch-menu" class="mobile-menu" href="#"><div class="mobile-logo">LOGO HERE</div><div class="mobile-menu-dropdown">MENU</div></a>
<div class="header-logo">LOGO HERE</div>
    <nav>
    <ul class="menu">
   <li><a href="#"></i>HOME</a>
   <li><a href="#"></i>ABOUT</a>
   <li><a href="#"></i>SOLUTIONS</a>
   <li><a href="#"></i>WORK</a>
   <li><a href="#"></i>CONTACT</a>
   <li><a href="#"></i><b>CLIENT AREA</b></a>
  </ul>
  </nav>

Answer №2

Click here to view the jQuery changes

In my modification of your jQuery, I implemented a click handler on the li element. For smooth scrolling to a specific part of the page, it is important to assign unique IDs to each div or section and link to those IDs like this:

   <a href="#contact">Contact</a>
   ...
   <div id="contact">
   ...
   ...
   </div>

If you require further explanation, feel free to ask!

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

Positioning the dropdown menu on the right with Boostrap 5.2 Navbar

After grappling with this problem for the past 72 hours, I've exhausted all my options and still can't seem to resolve it. I am currently working with Bootstrap 5.2 and have implemented a Navbar with a dropdown menu. My objective is to position i ...

How can you use Firestore to filter documents based on their presence in another collection?

For instance, I am looking to retrieve all users who are members of a certain "space". Here is a simplified Firestore rule example: match /users/{userId} { allow read: if exists(/databases/$(database)/documents/spaces/SPACEID/members/$(userId)); } Java ...

The attribute 'inventory' cannot be found in the declaration of 'WarehouseModule'

I am facing an issue with my AngularFire setup. I have recently installed the latest version of AngularFire using npm i @angular/fire and have successfully configured Firestore. However, when attempting to load data into my Firestore database, I encounte ...

Unable to display returned data from an AJAX request made with jQuery autocomplete

After reviewing the debug developer tool, I noticed that the ajax request returned data but for some reason, the data is not being displayed in the text box. The data contains special characters which are visible in the provided image. I am trying to iden ...

Black textures with images sourced from the same domain - Cross-origin

Despite trying numerous solutions and tips to resolve the cross-origin issue, I still can't seem to fix it. There are no errors, the images are hosted on the same domain as the webgl test, but the textures appear black. Occasionally when I refresh rep ...

Struggling to understand how to transfer data between two PHP files

I've been trying to send an array through POST and two variables through GET from first.php to second.php file, but I'm encountering an issue where I keep getting the error message Undefined index first.php <?php session_start(); $_S ...

What is the best way to remove input focus when clicked away?

I am in the process of developing an application using next js, and I need assistance with designing a search field. The primary functionality I am looking to implement is displaying search suggestions when the user starts typing, but hiding them when the ...

Ordering data in a dynamic table using JavaScript

After receiving an array of objects in the form of a JSON file and using AJAX to display specific key-value pairs in a table, I am now faced with the task of sorting the rendered table. However, I am uncertain about the steps to take next. <div id=" ...

Screenshots showcasing examples of HTML5 Canvas presentations

I recently discovered html2canvas through a question I had asked previously. I'm now trying to figure out how to use it to achieve the following: Generate a live thumbnail of a website. Clicking on the live thumbnail should load a larger image of th ...

"Components in Pusher and Vue.js seem to be stuck in the channel even with Vue Router in

I've integrated Pusher with Laravel Echo to establish presence channels for specific areas within my application. All navigation on the front-end is managed through Vue Router. I'm facing an issue where Vue Router loads components based on route ...

Exchanging Variables via Chrome Storage

I am looking for a solution to toggle a boolean value by clicking on an image. Every time the image is clicked, the state of the boolean value should change from true to false and vice versa. Here is an attempt at writing a function for this: function To ...

Attaching an event listener to elements with a specified Class name

Currently facing a challenge where I am trying to implement a function that captures click events on squares. The objective is to capture the click event on every button with the square class. import { Component, OnInit } from '@angular/core&apos ...

Is there a way to prevent both weekends and specific dates from being selected in the jQuery UI date picker?

Is it possible for the dates array to automatically check my Google Calendar for any scheduled dates? I would like to have those dates blocked off in my own calendar. <script> $(document).ready(function(){ var dates = ["06-08-2021"]; fun ...

I am having trouble with my custom-button class not successfully overriding the btn background color property. Can anyone provide insight

Utilizing the bootstrap5 variant-button mixin, I aim to create a custom-colored button. While I have successfully altered the default hover effect color, I am encountering difficulty in setting the background color of the button itself. Upon inspecting the ...

Why isn't the page being redirected when attempting to use JavaScript with window.location and window.location.href?

Currently, I have implemented a login system on my website. The process involves triggering an ajax request to a designated PHP script upon the user clicking the submit button. This script is responsible for logging in the user and responding with the mess ...

Pure CSS tab system that prevents label propagation using anchors

I am in the process of creating a tab system using only CSS with the help of the :target and :checked pseudo classes. However, I have encountered an issue where an anchor inside the label is not triggering the :checked. When clicking on the anchor, the :c ...

Ways to troubleshoot issues concerning z-index and overflow in CSS

Find my code in the sandbox: https://codesandbox.io/s/vibrant-microservice-4rplf I am working with select and modal components. Currently, when I click on the select component, it opens inside the modal causing a scroll to appear. https://i.sstatic.net/6 ...

The Bootstrap 4 alignment class for centering rows is not functioning as expected

<div class="row align-items-center remember"> <input type="checkbox" class="form-control" checked>Remember Me </div> <div class="row align-items-center"> <input type=& ...

Building a drop-right menu with Bootstrap within a dropdown menu - a step-by-step guide

I added a drop-down link to the site's navigation bar, but I'm trying to make one of the drop-down items a dropright link within another drop-down menu in the navigation bar. How can I achieve this? I tried using the code below, but the second d ...

Retrieve the Title from Tiles Option

Our automation team has requested that we hide the page names in a field on our page to assist them in verifying proper navigation. We rely on Apache tiles to build our pages using a layout of header, body, and footer, with most content residing in the bo ...