Tips on avoiding scrolling when toggling the mobile navigation bar:

While working on a website using HTML, CSS, and BS3, I have created a basic mobile navigation. However, I am facing an issue where I want to disable scrolling of the body when toggling the hamburger button.

The problem arises when the menu is toggled on, as it successfully prevents scrolling. But when the menu is toggled off, the scrolling functionality does not work.

Below is a snippet of the HTML code:

  <!--        mobile nav links-->
              <div class="mob-div-nav">
                <div class="row">
                  <div class="col-xs-12" style="height:100%;">

                  </div>
                </div>
              </div>
      <!--        END Mobile Nav-->

Additionally, here is the JavaScript code associated with this issue:

  $("#hamburger").on("click", function (event){

  $(".mob-div-nav").slideToggle(500);

  function noscroll() {
  window.scrollTo( 0, 0 );
}
  // add listener to disable scroll

  if ($(".mob-div-nav").css("display") == "block"){

    window.addEventListener('scroll', noscroll);

    } else if ($(".mob-div-nav").css("display") == "none") {

      window.removeEventListener('scroll', noscroll);

    }
});

Answer №1

Ensure you place the if statement inside the function, not outside. Your code should resemble this:

$(document).ready(function(){
  // #hamburger click event
  $("#hamburger").on("click", function (event){
    $(".mob-div-nav").slideToggle(500);
  }); // End of #hamburger click event
  // window scroll event
  $(window).on('scroll' , noscroll);
});

// functions here
// noscroll function
function noscroll() {
  if ($(".mob-div-nav").is(':visible')){
    window.scrollTo(0, 0);
  }
}

Explanation:

  • $(document).ready(function(){ - executes when the document is ready learn more
  • window.addEventListener pertains to pure JavaScript, while $(window).on('scroll' belongs to jQuery. Explore the differences between jQuery .on(); vs JavaScript .addEventListener();
  • .is(':visible'): a jQuery function that checks element visibility, :hidden for hidden elements, :checked for checked elements, etc. Learn more about .is() here

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

Repurposing React key usage

section, I am curious to know if it is standard practice to reuse a React key from one component to another. For instance, in the Row component, the key obtained from the Column component is reused for mapping the children of Row. const Table = props =& ...

Modifying the Ext.js TreePanel checkbox component

I've implemented a basic tree panel checkbox example using Ext.js as shown below: Ext.onReady(function(){ var tree = new Ext.tree.TreePanel({ renderTo:'tree-div', title: 'My Task List', height: 300, ...

Struggling to convert a JSON file into a TableView within a JavaScript application developed with Appcelerator

Trying to display a JSON file in a table using JavaScript and Appcelerator is proving to be quite a challenge. The output appears as an empty table when compiled to an example page. As someone relatively new to JavaScript and JSON, I'm seeking guidanc ...

navigate a specific web address using Express routing

Is there a specific regex pattern that should be used in an Express application to match a URL? For example, if the endpoint is www.mydomain.com/v1/https://www.url-to-be-matched.com. I am aiming to accept https://www.url-to-be-matched.com as parameters. H ...

Sending an object over to a different page

Need some assistance with displaying JSON data that is being repeated using ng-repeat. { "title": "image title", "description": "Lorem ipsum dolor sit amet, per ea ferri platonem voluptaria, ea eum ubique ornatus interpretaris. Dolore erroribus reprimique ...

Testing an async function with Jest - Jest failed to exit within one second of completing the test

Looking to validate the functionality of my Next.js API functions using Jest along with node-mocks-http. The specific function I aim to test is as follows: export default async ( req: NextApiRequest, res: NextApiResponse ): Promise<void> => { ...

Encountering issues when implementing react-router with the client-side library

After following the author's suggestion, I've successfully loaded the client-side library. The recommended method is to simply drop a <script> tag in your page and use the UMD/global build hosted on cdnjs. I have ensured that ReactRouter i ...

What is causing the TouchSwipe jQuery plugin not to function in my code?

I have integrated the TouchSwipe jQuery plugin into my code to detect mouse movement and display the number of pixels moved when swiping left or right. To download the TouchSwipe jQuery plugin, I visited this link: TouchSwipe and then proceeded to use it ...

What is the process for incorporating ejs into the source attribute of an image element?

Code Snippet: <img class="card-img-top" alt="..."><%= articles.image %><img> Server Setup: const express = require('express') const app = express() const router = require('./routes/article') app ...

Sorting through names within a nested array based on specific criteria

I have been struggling to filter by item name for the past day and haven't been successful. The issue lies in my attempt to use a sample array for filtering. While I am able to filter by category successfully, the same cannot be said for filtering by ...

jQuery Conditional String Manipulation

I have set up a system where users can input values and make selections from a drop-down menu, which then get integrated into JavaScript code to generate customized sentences based on their inputs. Once the user clicks submit, the sentence is formed. It&ap ...

What is the best way to retrieve an AJAX response in advance of sending it to a template when utilizing DATAT

Recently, I've been working on integrating log tables into my admin panel using the datatable plugin. Despite setting up an ajax call in my datatable, I'm facing issues with retrieving the response before sending it to the table. Here's a s ...

There seems to be an issue with the accurate calculation of the screen width while utilizing the scrollbar-gutter

Please take note: The scrollbar-gutter: stable; property is not compatible with Safari. Additionally, the issue seems to be specific to Chrome and works fine in Firefox. I have observed some unusual behavior when attempting to position elements fixed to t ...

Database only accepts numerical data for insertion, rejecting any characters or alphanumeric entries

On a webpage, I have an input field through which I am passing the value into an ajax POST request. After logging everything in my JavaScript file and confirming that all is working as expected. In my PHP file, I retrieve the input value using $message = ...

Random sequencing of the commands

Whenever I call the Details function, it returns empty details because the function executes before retrieving data from the json file. What is the best way to fix this issue? app.controller('loginCtrl',function($scope,login){ $scope.user=login ...

Template string use in Styled Components causing issues with hover functionality

I have a styled component where I am trying to change the background color when its parent is hovered over. Currently, the hover effect is not working and I'm unsure why. const Wrapper = styled('div')` position: relative; margin-bott ...

Remove newline character from HTML code using Python 3.2 and urllib module

After fetching HTML content as a string using urllib, I encountered difficulty in searching the string due to its HTML format. Is there any way to "unformat" the string by removing all the new lines without altering the HTML code itself? Here is the Pytho ...

Creating synchronization mechanisms for events in JavaScript/TypeScript through the use of async/await and Promises

I have a complex, lengthy asynchronous process written in TypeScript/JavaScript that spans multiple libraries and functions. Once the data processing is complete, it triggers a function processComplete() to indicate its finish: processComplete(); // Signa ...

Issue: The initiation function fails to start data

I have created an app using Ionic framework that displays articles. When a single article is opened, I use the init function in the UserService to initialize user data: angular.module('coop.services') .factory('UserService', function( ...

The Selenium Webdriver's isSelected() method in Chrome browser does not return true for radio buttons

I have been attempting to confirm whether my radio button is selected or not, but I keep receiving a false value even after selecting the radio button. Here is the HTML code: <div class="controls tss-radio-text-format"> <label class= ...