Switching the navigation menu using jQuery

I am looking to create a mobile menu that opens a list of options with a toggle feature.

I want the menu list to appear when the toggle is clicked, and I also want to disable scrolling for the body. When the toggle menu is clicked again, the list should close, enabling scrollability for the body once more.

Is there a way to achieve this functionality?

Here is my code:

<body class="cbp-spmenu-push">

<div class="headerArea clearfix">
<div class="LogoArea"> <a href="#"><img src="images/smallogo.png" width="100"></a> </div>
<div class="container">
       <section>
           <div class="main">
               <div class="toggle_menu" id="showRight"> 
                    <i></i>
                    <i></i>
                    <i></i> 
               </div>
           </div>
       </section>
</div>
<div class="menuArea">
    <nav class="cbp-spmenu cbp-spmenu-vertical cbp-spmenu-right" id="cbp-spmenu-s2">
            <a href="#">COMPANY</a>
            <a href="#">PRODUCTS</a>
            <a href="#">INTERNATIONAL</a>
            <a href="#">BUSINESS OPPORTUNITIES</a>
            <a href="#">CAREER</a>
            <a href="#">CONTACT</a>
        </nav>
    </div>
</div>
</body>

CSS:

.cbp-spmenu,
.cbp-spmenu-push {
    -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    transition: all 0.3s ease;
}

Javascript:

<script>
    $(document).ready(function(e){
        $('.toggle_menu').click(function(){
            $('body').css("overflow","hidden")
        });
    });
</script>

The current jQuery code successfully disables scrolling when the toggle menu is clicked. However, it does not re-enable scrolling when the menu list is closed.

Any assistance on how to achieve this functionality would be greatly appreciated.

Answer №1

Utilize the .toggleClass() function to easily add or remove a CSS class from an element.

You can define a CSS class with properties such as overflow: hidden and then use toggleClass in jQuery to dynamically apply or remove this class.

$(document).ready(function(e) {
  $('.toggle_menu').click(function() {
    $('body').toggleClass("overflow");
  });
});
.cbp-spmenu,
.cbp-spmenu-push {
  -webkit-transition: all 0.3s ease;
  -moz-transition: all 0.3s ease;
  transition: all 0.3s ease;
}
.overflow {
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<body class="cbp-spmenu-push">
  <div class="headerArea clearfix">
    <div class="LogoArea">
      <a href="#">
        <img src="images/smallogo.png" width="100">
      </a>
    </div>
    <div class="container">
      <section>
        <div class="main">
          <div class="toggle_menu" id="showRight">Click Here
            <i></i>
            <i></i>
            <i></i> 
          </div>
        </div>
      </section>

    </div>
    <div class="menuArea">
      <nav class="cbp-spmenu cbp-spmenu-vertical cbp-spmenu-right" id="cbp-spmenu-s2">
        <a href="#">COMPANY</a>
        <a href="#">PRODUCTS</a>
        <a href="#">INTERNATIONAL</a>
        <a href="#">BUSINESS OPPORTUNITIES</a>
        <a href="#">CAREERS</a>
        <a href="#">CONTACT</a>
      </nav>
    </div>
  </div>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
</body>

Answer №2

$('.toggle_menu').click(function(){
     $('body').css("overflow","hidden")
});

When implementing the function above, it is important to first check whether the toggle_menu is open or closed. Based on this condition, adjust the body's overflow property to either 'hidden' or 'auto'. Here is an example:

$('.toggle_menu').click(function(){
    if ('.toggle_menu.active') {
         $('body').css("overflow","hidden");
    } else {
         $('body').css("overflow","auto");
    }

});

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

Creating Browser Extensions with Vue.js and Vue CLI

I am in the process of creating a Chrome Extension with a frontend powered by Vue.js. Everything was going smoothly using vuecli until my app started utilizing the Webextension-API. This API is only accessible to registered Extensions, not normal websites. ...

A guide on accessing a dynamic object key in array.map()

How can I dynamically return an object key in array.map()? Currently, I am retrieving the maximum value from an array using a specific object key with the following code: Math.max.apply(Math, class.map(function (o) { return o.Students; })); In this code ...

Sorting rows by words and numbers in JavaScript explained

Hello, I'm a beginner and I need help sorting the table rows in the following table. I also want to attach an onclick listener to the header after it is displayed. ID Name Inventory Volume 1 Rachel Data is not enough 2 Ross 100 3 Monica 1 ...

Enhance the current menu item in WordPress by assigning a class to the anchor tag

function updateActiveClassOnMenu($item_output, $item, $depth, $args) { $menu_locations = get_nav_menu_locations(); if ($item->menu_order == 1){ $item_output = preg_replace('/<a /', '<a class="active" ', $item_o ...

Increase the size of the SVG area

I'm still learning how to work with SVGs, so I appreciate your patience as I ask what may seem like a simple question. Currently, I have an SVG image that resembles a cake shape. See it here: https://i.sstatic.net/tDhUL.png Take a look at the code: ...

Can Vue support recurring time slots?

I have configured a reproduction repository: https://github.com/devidwong/recurring-slot Using Vue runtime-only, I am unable to use Vue.extend (which requires template compiler) Vue 3 is quite new to me. I decided to use it for exploration purposes. Not ...

Postponed in JQUERY | AJAX

My requirement is to retrieve data using the "SetUnit()" function, which includes asynchronous AJAX services. I attempted to use Deferred as suggested in this link, but it did not work for my needs. Code...... Function function SetUnit(query) { var ...

Postal Code Auto-Suggest by Google

I'm attempting to create a unique autocomplete feature for a text box that specifically provides postal codes. To accomplish this, I have followed the guidelines outlined in the documentation found at https://developers.google.com/places/webservice/au ...

Unable to assign a className to a personalized React component - troubleshooting needed!

I have a component that relies on another component. I am trying to pass CSS positioning from the outer component to the inner one by using the following code: import OptionsMenu from './OptionsMenu' import { withStyles } from 'material-ui/ ...

Methods for adjusting columns and rows in HTML5 tables

As I was preparing to create a compatibility guide, I noticed that the HTML code consisted of a table. While tables are effective for displaying data, they can be cumbersome to edit frequently. What tools are available to quickly and cleanly edit an exist ...

Utilizing AJAX and javascript for extracting information from websites through screen scraping

Is it possible to scrape a screen using AJAX and JavaScript? I'm interested in scraping the following link: I tried the technique mentioned on w3schools.com, but encountered an "access denied" message. Can anyone help me understand why this error is ...

Digital Repeater and Angle Measurer

Seeking Guidance: What is the recommended approach for locating the Virtual Repeaters in Protractor? A Closer Look: The Angular Material design incorporates a Virtual Repeater to enhance rendering performance by dynamically reusing visible rows in the v ...

What steps can be taken to resolve an ESLing error in this situation?

Check out this code snippet: <template v-if="isTag(field, '')"> {{ getItemValue(item, field) ? getItemValue(item, field) : '&#8211'; }} </template> An issue has been identified with the above code: Er ...

I need help establishing a distinct GMT end time for the classyCountdown.js plugin

Regarding the jquery countdown plugin found at this link, The current trigger code only sets a target end time based on the page load, and I am looking to set it relative to a specific GMT/UTC date and time. $('.countdown').ClassyCountdown({ ...

ion-grid featuring alternate columns

As someone who is not very familiar with Angular, I am trying to create a grid layout like the one shown here: https://i.stack.imgur.com/nBavk.png The desired layout includes alternating rows with one image followed by two images. My current attempt at a ...

Adjust SVG size to fit parent container/division

I am trying to make the SVG completely fill the containing TD. I don't care about preserving the proportions of the SVG. Instead, I want the height of the SVG to be the same as its width when the height should be larger than the width. There is paddin ...

Create an element that can be dragged without the need to specify its position as absolute

I am having an issue where elements I want to drag on a canvas are not appearing next to each other as expected. Instead, they are overlapping: To make these elements draggable, I am utilizing the dragElement(element) function from https://www.w3schools.c ...

How to call a function within a component from another component without encountering the "Cannot read property" error

Having trouble calling a function from one component in another by passing the reference of one to the other. I keep getting a "Cannot read property" error. Below is the code snippet Alert Component import { Component, OnInit, Output } from '@angula ...

Disable Autocomplete Chip functionality when only one can be selected

When multiple is set to true, I prefer the Chip option. Is there a way to enable the Chip functionality even when multiple is set to false? <Autocomplete className={classes.search} options={top100Films} ge ...

Pressing the HTML button will reveal the cart details in a fresh display box

I have been working on setting up a button to display the items in the shopping cart. I have successfully created the cart itself, but now I am facing the challenge of creating a button called showYourCart that will reveal a box containing the cart detai ...