Navigating a mobile-friendly menu anytime!

I'm in the process of creating a responsive "hamburger" menu for mobile devices. The HTML code I have implemented is as follows...

.menu_closed {
  color: red;
}
.menu_open {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
  $('span.menu_closed').click(function() {
    $('ul.menu').toggle('1000');
    $(this).toggleClass("menu_open menu_closed");
  });
</script>
<span class="menu_closed">&#9776;</span>
<ul class="menu" id="menu">
  <ul class='section' id='section_1'>
    <li><span id='section_title_1' class='section_title'><a href='#' id='section_link_1'>Against the odds.</a></span>
      <ul>
        <li id='exhibit_1' class='exhibit_title'><a href="../against-the-odds/introduction"> &rarr; Introduction</a>
        </li>
        <li id='exhibit_2' class='exhibit_title'><a href='../against-the-odds/deriving-functions'> &rarr; Deriving functions</a>
        </li>
        <li id='exhibit_3' class='exhibit_title'><a href='../against-the-odds/exploiting-odds'> &rarr; Exploiting odds</a>
        </li>
        <li id='exhibit_4' class='exhibit_title'><a href='../against-the-odds/betting_history'> &rarr; Betting history</a>
        </li>
      </ul>
    </li>
  </ul>
  <ul class='section' id='section_2'>
    <li><span id='section_title_2' class='section_title'><a href='http://themathsproject.co.uk' id='section_link_2'>Remembering everything.</a></span>
      <ul>
        <li id='exhibit_104' class='exhibit_title'><a href='#'>black swans</a>
        </li>
      </ul>
    </li>
  </ul>
  <ul class='section' id='section_5'>
    <li><span id='section_title_5' class='section_title'><a href='http://themathsproject.co.uk' id='section_link_5'>Running faster.</a></span>
      <ul>
        <li id='exhibit_107' class='exhibit_title'><a href='#'>possible areas to explore</a>
        </li>
        <li id='exhibit_108' class='exhibit_title'><a href='#'>developing the model</a>
        </li>
        <li id='exhibit_109' class='exhibit_title'><a href='#'>performance</a>
        </li>
      </ul>
    </li>
  </ul>
  <ul class='section' id='section_4'>
  </ul>
  <div class='bot'>
    <p><a href='https://www.twitter.com/themathsproject' target="_blank">twitter</a>
      <br />
      <a href='https://www.facebook.com/themathsproject' target="_blank">facebook</a>
    </p>
  </div>
</ul>

Unfortunately, the menu is not behaving as expected and I am unsure of what went wrong.

If anyone could provide assistance, I would greatly appreciate it.

Sincerely, Jack

Answer №1

A better approach would be to use a standard menu class like <code>.hamburger
instead of .menu_closed. This way, if you decide to change it to .menu_open, the click handler will still work as expected.

The line

$(this).toggleClass("menu_open menu_closed");
should simply toggle a generic class such as open or closed. While your original method may have worked, it's best practice to name the menu class in a more flexible way.

I've also added cursor: pointer; to the menu CSS to provide a visual cue to users that the element is clickable.

It's important to wrap your jQuery code in $(function() {}); to ensure that it runs only after the DOM has loaded completely. This ensures that the elements your script interacts with are available.

Furthermore, I've updated the click handler from using $.live() which is deprecated to $.on() per the latest jQuery recommendations. Using $.on() is the modern way to attach event handlers.

.hamburger {
  color: red;
  cursor: pointer;
}
.open {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
  $(function() {
    $('.hamburger').on('click', function() {
       $('ul.menu').toggle(1000);
       $(this).toggleClass("open");
    });
  });
</script>
<span class="hamburger">&#9776;</span>
<ul class="menu" id="menu">
  <ul class='section' id='section_1'>
    <li><span id='section_title_1' class='section_title'><a href='#' id='section_link_1'>Against the odds.</a></span>
      <ul>
        <li id='exhibit_1' class='exhibit_title'><a href="../against-the-odds/introduction"> &rarr; Introduction</a>
        </li>
        <li id='exhibit_2' class='exhibit_title'><a href='../against-the-odds/deriving-functions'> &rarr; Deriving functions</a>
        </li>
        <li id='exhibit_3' class='exhibit_title'><a href='../against-the-odds/exploiting-odds'> &rarr; Exploiting odds</a>
        </li>
        <li id='exhibit_4' class='exhibit_title'><a href='../against-the-odds/betting_history'> &rarr; Betting history</a>
        </li>
      </ul>
    </li>
  </ul>
  <ul class='section' id='section_2'>
    <li><span id='section_title_2' class='section_title'><a href='http://themathsproject.co.uk' id='section_link_2'>Remembering everything.</a></span>
      <ul>
        <li id='exhibit_104' class='exhibit_title'><a href='#'>black swans</a>
        </li>
      </ul>
    </li>
  </ul>
  <ul class='section' id='section_5'>
    <li><span id='section_title_5' class='section_title'><a href='http://themathsproject.co.uk' id='section_link_5'>Running faster.</a></span>
      <ul>
        <li id='exhibit_107' class='exhibit_title'><a href='#'>possible areas to explore</a>
        </li>
        <li id='exhibit_108' class='exhibit_title'><a href='#'>developing the model</a>
        </li>
        <li id='exhibit_109' class='exhibit_title'><a href='#'>performance</a>
        </li>
      </ul>
    </li>
  </ul>
  <ul class='section' id='section_4'>
  </ul>
  <div class='bot'>
    <p><a href='https://www.twitter.com/themathsproject' target="_blank">twitter</a>
      <br />
      <a href='https://www.facebook.com/themathsproject' target="_blank">facebook</a>
    </p>
  </div>
</ul>

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

Displaying the data from a database on a browser using node.js, MySQL, and Jade

Currently, I am delving into Node.js, Express.js, and Jade while utilizing a MySQL database. As a newcomer to node.js, I decided to start with something simple: presenting data from the database in a table on the browser. Unfortunately, my attempts have no ...

What could be the reason for the unexpected behavior of position sticky?

I am encountering an issue while trying to figure out why the container__item--special element behaves as a sticky element in this code snippet <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> ...

The error message "Uncaught TypeError: Cannot set property 'map' of undefined" occurs when using the callback function to load a texture with Three.js TextureLoader

Currently working with Three.js and aiming to refactor the code. I am looking to create a dedicated class called "Floor" for generating floors: import { Mesh, MeshBasicMaterial, PlaneGeometry, RepeatWrapping, sRG ...

Customize the background image in your Windows 8 app developed with HTML

While working on my app with the grid app template, I placed an image in the images folder. However, when I attempted to change the background image, it didn't seem to take effect. This is the code snippet that I used: HMTL <div id="contenthost" ...

What is the optimal method (best practice!) for generating a react component following an onClick event?

I have recently started teaching myself Reactjs and have encountered a problem. I am stuck and would like to know how I can create a new <div> in the DOM when I click on a button. When using pure JS, I used an addEventListener on a button to add / r ...

Declining Effects of AJAX using jQuery

Hi there, I am currently working with an AJAX script that is a combination of jQuery 1.4.4 and jQuery address 1.3.2. What I'm trying to achieve is to make the transitions between divs more smooth by fading them in and out instead of just changing abru ...

The node.js application was unable to locate the '../HMS/server/models/user' file

Hi there! I'm currently working on an application with a folder structure as shown below. I want to use the following line in my passport.js file: var User = require('../server/models/user'); However, I encountered the error below after tr ...

Dim the brightness of an image on Internet Explorer

I discovered this code on another site and it functions flawlessly in Chrome and FF, however, IE (version 11.0.9) doesn't seem to like it. -webkit-filter: grayscale(0%); -moz-filter: grayscale(0%); -o-filter: grayscale(0%); filter: grayscale(0%); fil ...

In AngularJS, the execution of a subsequent AJAX call is reliant on the response of a preceding AJAX

Initially, I invoked the userSignupSubmit function. Within this method, another method called mobilenocheckingmethod is called. This method depends on the response from an AJAX call to make another AJAX call, but unfortunately, the second call does not w ...

Fixed-top navbar in Bootstrap obscuring webpage contents

I have tried various solutions to the issue at hand, but nothing seems to be working. I applied padding-top to the container of my main content, but when I add the following CSS: @media (max-width: 768px) { body{ padding: 0; } } it overrides the padd ...

What is the best way to fill a list-group using JavaScript?

Fetching ticket data from a controller is done using the code snippet below: $.ajax({ type: "GET", url: "/Tickets/List/", data: param = "", contentType: "application/ ...

Uploading Multiple Images using Ajax in Laravel 5.6

I would like to start off with an apology for any grammatical errors in my writing. One thing I want to clarify is that I prefer not to utilize any plugins. My goal is to be able to upload multiple images using Ajax, even though I currently have a method ...

Angular2 only supports cross-origin requests for protocol schemes

I'm currently facing an issue while following the Angular Quickstart tutorial due to a CORS error. To resolve this, I made configurations in my Windows host file located under system32/drivers/etc/: 127.0.0.1 tour-of-heroes I also configured ...

Issue involving retrieving keys from multiple classes in a JSON object

I am facing some difficulties with JSON and JavaScript as I am a beginner in this area. Currently, I am attempting to iterate through all the keys["name"] of this JSON data. var l = [{ "pages": [ { "name": "Scan", "elements": [ { "type": ...

Using form submission to implement reCAPTCHA v3 in g-recaptcha

Is the Recaptcha API causing trouble? I have the key on both the submit button and the form tag, but it's only sending the sitekey without generating tokens. Any suggestions are welcome. You can either use the key in the form tag: <form method=&qu ...

Streamlined [JavaScript?] solution for displaying and modifying several location-specific purchasing and selling rates

No, this is not related to interviews or cryptocurrencies! :) It is for a non-profit personal web application designed to enhance a game. This question involves both finance and coding. I am developing this web app using Vue.js, so I prefer a JavaScri ...

How about incorporating two subtly tilted SVGs for a creative twist on navigation backgrounds?

I am in the process of designing the navigation menu for my website and I have a specific vision in mind. I want to create a unique background using two rectangular SVGs that are slightly rotated off axis and overlapping each other, with their edges extend ...

What can cause the reactive value to fail to update in a Vue template?

In my application, I encountered a strange issue where a h3 tag containing a title bound to a reactive data property from a Firestore database would sometimes not display properly after a page reload. Oddly enough, when accessing the page through client-si ...

Issue with displaying value after rendering

After fetching pool data from the constants file, my task was to create a featured vault - the one with the highest APY Reward value obtained from the API. Even though I successfully fetched all three values and performed the calculations, I am facing an i ...

Avoid using fs.read without returning a value to console.log

Seeking assistance with parsing a text file named information.txt and displaying the values using console.log. Here is the code snippet: fs.readFileSync("information.txt", "utf-8", function (err, data) { ...