What is the best way to create a mobile menu button that shows and hides the navigation bar, and also disappears when clicked on in an empty space?

Recently, I've been working on creating a responsive website and have managed to sort out most of it. However, I am facing some difficulty in making the menu button (which appears on specific devices according to media queries) toggle the navigation bar display.

After doing some research, it seems like the only way to achieve this is through JavaScript. Is that correct?

Despite my limited knowledge of JS, I tried implementing it as I thought it would work. Here's a snippet of the code I used. The concept is that when ".menu-icon" is clicked, the menu should drop down (or fade in) and then hide again with a second click, and so on.

http://jsfiddle.net/af57r1to/

<div id="logo">
  <a href="#">
    <img class="logo" src="images/logo.png" alt="Logo" style="width:200px;height:100px" />
  </a>
  <a class="menu-icon" href="#menu">&#57349;</a>

  <br></br>
</div>
<div class="navbar">
  <ul class="navbar cf">
    <li><a href="index.html">HOME</a>

    </li>
    <li><a href="#">SECTIONS</a>

      <ul>
        <li><a href="retail.html">RETAIL </a>

        </li>
        <li><a href="#">HOTEL</a>

        </li>
        <li><a href="#">RESTAURANT</a>

        </li>
        <li><a href="#">SHOPPING</a>

        </li>
      </ul>
      <li><a href="how.html">HOW IT WORKS</a>

      </li>
      <li><a href="#">OUR EXPERIENCE</a>

      </li>
      <li><a href="#">TESTIMONIALS</a>

      </li>
      <li><a href="#">NEWS</a>

      </li>
      <li><a href="">CONTACT US</a>

      </li>
  </ul>
</div>

<br />



$(document).ready(function () {
    $('.menu-icon').click(function () {
        $('.navbar').fadeToggle(); 
    });  
});

Currently, the navigation fades in for about 0.3 seconds and then disappears, not giving users enough time to make a selection from the dropdown menu. I believe there might be something obvious that I missed. Any assistance in fixing this issue would be greatly appreciated.

Answer №1

If you're experiencing issues with the toggle feature when removing the navbar class from navbar cf, try assigning an id to your navbar element for a solution without compromising styling.

<div class="navbar" id='uniqueNavbarID'>
    <ul class="navbar cf">
        <li><a href="index.html">HOME</a>

Then, use this code snippet:

$('.menu-icon').click(function () {
    $('#uniqueNavbarID').fadeToggle();
});

For reference, check out the JSFiddle provided here.

Answer №2

Your code has some mistakes in both the HTML and JS sections.

First of all, you opened a <ul> element inside a <li> element but then closed it outside of the <li>. This breaks the structure of the elements. The closing tag for the <ul> should be inside the <li> where it was opened.

Secondly, the $(document).ready() function is not properly closed:

$(document).ready(function () {
    $('.menu-icon').click(function () {
        $('.navbar').fadeToggle();
    });
});

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

To ensure compatibility with Angular, the data path "/fileReplacements/1/replace" should adhere to the pattern ".(([cm]?j|t)sx?|json)$"

After upgrading Angular from version 10 to 14, I encountered an issue in the build process related to replacing the favicon.ico using fileReplacements like so: "fileReplacements": [ { "replace": "src/favicon.ico", ...

Is there a way to dynamically alter the theme based on stored data within the store

Is it possible to dynamically change the colors of MuiThemeProvider using data from a Redux store? The issue I'm facing is that this data is asynchronously loaded after the render in App.js, making the color prop unreachable by the theme provider. How ...

Extracting the best results using Selenium in Python

I am currently attempting to use Selenium to search for a term and retrieve a list of the top URLs from the search results. Although I am new to Selenium and still learning, I have been following a tutorial found here: https://www.youtube.com/watch?v=EELyS ...

When I use my loop to generate Google Map markers, the positioning is not accurate and the markers do not appear on the map. However, manually inputting the positions

There seems to be an issue with displaying Google map markers based on objects in the markers array after looping through it. I noticed that when creating a second component and setting the position manually, the marker appears correctly. However, upon ins ...

Using Javascript, capture user input to execute a search function without the need for a submit button

I am attempting to retrieve input from a textbox and utilize that value to conduct a search without the need for a submit button. The goal is for the search results to be displayed on the page as soon as the content in the textbox changes. I have been br ...

The alignment of the text is incorrect and needs to be fixed

In my code, I have an if statement that determines how the page should be rendered. <script language="JavaScript"> if (NS4) { document.write('<LAYER NAME="floatlayer" LEFT="22" TOP="60">'); } if ((IE4) || (NS6)) { document.w ...

Locate the parent element using a unique child element, then interact with a different child element

Can you help me come up with the correct xpath selector for this specific element? The element only has a unique href. Is it possible to locate the element by searching for the text iphone X within the href="#">iphone X and also checking for its paren ...

When using the `survey-react` package, there seems to be an issue with the `this.addEvent

Upon inheriting a React project, I am facing difficulty in utilizing the survey-react module. Every time I access http://localhost:3000/, I encounter this error: Uncaught TypeError: this.addEvent is not a function node_modules/survey-react/survey.react.js: ...

Execute script when on a specific webpage AND navigating away from another specific webpage

I created a CSS code that adds a fade-in effect to the title of my website, and it works perfectly. However, I now want to customize the fade-in and fade-out effect based on the page I am transitioning from. My desired outcome: If I am leaving the "Biolo ...

Using Jquery to interact with a pop-up window

My website contains JQuery code that is loaded onto a webpage. This page also features a link that opens a popup window. I encountered an issue while trying to use the loaded JQuery code to interact with elements on the popup page. To resolve this issue f ...

The Viadeo Social Toolbox seems to be encountering technical difficulties at the moment

I attempted to utilize a Viadeo Social Toolbox, specifically the Viadeo Share Button, but it seems to be malfunctioning in certain browsers? I came across some outdated viadeo share URLs like this: http://www.viadeo.com/shareit/share/?url=${url}&title ...

Ensure the most recently expanded item appears at the top of the TreeView by updating to Mui version

I'm working on a feature where I want to scroll the expanded TreeItem to the top when it has children and is clicked on for expansion. Any suggestions on how to make this happen? ...

Contrasting the use of ajax versus post back for executing actions

My question may seem a little unusual, as it involves the AJAX approach. I simply repurposed an original function that I came across, renamed it, and tested it. In a more common scenario: There are a few <asp:TextBox> controls and one submit butto ...

Encountering an error stating "cloudinary.uploader is undefined" while attempting to delete media files from Cloudinary

I'm currently developing a web application using express and node.js. In my project, I'm utilizing cloudinary for uploading media files. While uploading and accessing media works smoothly, I'm encountering an issue with deleting images from ...

Ensure the modal content is loaded only when the modal is being displayed, not

I currently have a basic CSS-styled modal that appears when a button is clicked using JavaScript. Here is the JavaScript code: <script> var modal = document.getElementById('myModal'); var btn = document.getElementById("myBtn"); var span = ...

Struggling to extract a specific value from a JSON string?

I am trying to retrieve the first element of a JSON object, but using data.first returns nothing. However, when I use alert(data), it prints the full JSON string. Can someone please help me troubleshoot this? <?php include_once '../con_db.php&apo ...

Ways to retrieve the currently selected id from the router within the next 14 steps

I'm currently trying to extract the ID that is selected (#about, #home, #blog) or the full path (http://localhost:3000/#about, http://localhost:3000/#home) from the router. I am working with Next.js version 14.0.3 This is my approach: My current URL ...

Is there a way to make a Bootstrap grid with four columns span across two rows in the second column?

How can I create a Bootstrap grid with four columns where the second column spans two rows? Hello, I am looking for help to achieve a portfolio grid layout with 4 columns (refer image here) and have the second column span 2 rows. I plan to include images ...

Guide on expanding the capabilities of IterableIterator in TypeScript

I am currently working on extending the functionality of Iterable by adding a where method, similar to C#'s Enumerable.where(). While it is straightforward to extend the Array prototype, I am encountering difficulties in figuring out how to extend an ...

Replacing an array in Perl with the contents of a SQL database: A step-by-step guide

Update: (Check Revised Code at the bottom) The code is now functioning properly to retrieve data from 2 databases with some additional cleaning required. However, I'm facing a challenge where the code previously used: next unless $currentuser ~~ @las ...