Stop the body from scrolling when the side panel is opened

Whenever I click on my button with the class "cd-btn," it triggers the toggling of my panel with the class "cd-panel.is-visible."

 jQuery(document).ready(function($){
//open the lateral panel
$('.cd-btn').on('click', function(event){
    event.preventDefault();
    $('.cd-panel').toggleClass('is-visible');
});

The class ".is-visible" is defined as:

 .cd-panel.is-visible {
  visibility: visible;}

To prevent the body from scrolling when the panel is open or visible, I currently use the following code:

$(".cd-panel").mouseenter(function(){
  $("body").css("overflow", "hidden"); 
}).mouseleave(function(){
  $("body").css("overflow", "visible");
});

However, this method only works when I hover over the panel with my mouse. I am looking to achieve the same effect when opening the panel itself. How can I set the body to have overflow:hidden when the panel opens, and then switch it back to overflow:visible when the panel is closed? Additionally, I would like to set the body's position to fixed when the panel is open, and back to relative when the panel is closed.

Answer №1

After reading the comments from you and @Praveen-Kumar, I think I've identified the issue.

Instead of using the :visible selector, it would be better to check if the element contains the class is-visible to determine visibility.

Your revised code should look like this...

$('.cd-btn').on('click', function(event){
  event.preventDefault();
  $('.cd-panel').toggleClass('is-visible');
  if ($('.cd-panel').hasClass("is-visible")) // Modified this line based on your feedback.
    $("body").css("overflow", "hidden");
  else
    $("body").css("overflow", "visible");
});

Answer №2

Insert the .css code below:

$('.toggle-btn').on('click', function(e){
  e.preventDefault();
  $('.panel').toggleClass('show');
  if ($('.panel').is(":visible"))
    $("html").css("overflow", "hidden");
  else
    $("html").css("overflow", "visible");
});

Answer №3

$('.cd-btn').on('click', function(event){ 
    event.preventDefault(); 
    $('.cd-panel').toggleClass('is-visible'); 
    if ($('.cd-panel').hasClass("is-visible")) { 
        $('body').css({
            height: '100%',
            overflow: 'hidden'
        })
    } else {
        $('body').css({
          height: 'auto',
          overflow: 'visible'
        }) 
    }
});

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

Struggling to link an external JavaScript file to your HTML document?

While attempting to run a firebase app locally, I encountered an error in the chrome console: GET http://localhost:5000/behaviors/signup.js net::ERR_ABORTED 404 (Not Found) Do I need to set firebase.json source and destination under rewrites or add a rout ...

Altering the text of dropdown items prior to the ASP.NET autopostback

Recently, I inherited a project from a client that is plagued with some irritating issues. One particular problem involves a dropdown menu that triggers an autopostback event upon selection change, inserting the selected text into a T-SQL query. The troubl ...

Calculate the total price using jQuery

I’m a beginner in JavaScript and I’ve hit a roadblock. I have a plus and minus button that adds up product quantities, but I need the total price to reflect this as well. Some products can only be purchased in multiples of 2, 5 or 10. Here is the HTML ...

Is there a feature on the webpage that allows users to save clicked xy points and display them as text?

Is there a way to incorporate a feature on a website that displays clicked xy points as text, allowing them to be easily copied and pasted? ...

Is there a way to right-align the labels and input fields simultaneously?

Is there a way to line up the labels and inputs on the right side so they all appear in the same row? .radioContainer{ width: fit-content; margin: 5px; margin-top: 20px; background-color: aqua; padding-bottom: 25px; } <div class=" ...

Issues with Bootstrap's center-block functionality

I'm having trouble centering the navigation in my WordPress template that uses Bootstrap. I've tried using the center-block class on different elements, but the menu items are still aligning to the left. I even created a custom class in my custom ...

How to Efficiently Organize OpenAI AI Responses Using TypeScript/JavaScript and CSS

I'm using a Next.js framework to connect to the OpenAI API, and I've integrated it seamlessly with an AI npm package. The functionality is incredible, but I've encountered an issue regarding line breaks in the responses. You can find the AI ...

Perform a function on Angular 5

In my database, there is a table named settings. I have 2 backend endpoints: one for getting settings and another for updating settings. Now I am working on creating an Angular window to edit this table. I've set up an Angular Service to retrieve va ...

What steps should be taken to create a two-column table from a given list of items?

I am trying to display a list of words in two columns, one word after another from left to right. Here is the desired table structure: <table id="wordTable"> <tr> <td>ac </td> <td>bd </td> </tr> ...

Eclipse Content Assist feature appears to be malfunctioning as it fails to display

Having an issue with Eclipse on Win 10 (64bit) when working with JavaScript projects. I've tested this problem on both Eclipse Photon and version 2018-09 (64 bit versions) and encountered the same problem on both instances: After creating a new JavaS ...

Utilize JQuery's .load() function to transmit JSON data to your Flask server

I am attempting to utilize JQuery's .load() function in order to transmit data to my Flask server and then, with that information, display a <div> that is loaded into the element making the request. This is what my code snippet looks like: $(&qu ...

Utilize Jquery to insert the text into the input or textarea field

<div class="ctrlHolder"> <label for="" id="name.label">Name</label> <input name="name" id="name" type="text" class="textInput small" /> <p class="formHint">Please enter the name of the item you are submitting</p> </di ...

Adjusting the width of a product slider based on window size changes using CSS media queries

Currently, I have a functional product slider that I am attempting to adjust the width for smaller viewports, but it is proving to be a challenge. Upon loading the document, the code tallies the width of each product item and initiates slides when buttons ...

Is the ID "nodeName" specifically designated as reserved in the HTML5 language specifications?

I have an element with the following id: <span id="nodeName"></span> In my HTML code. Then, when using jQuery to do the following: $("#nodeName").html("someString"); I am getting an error in the console that says: Uncaught TypeError: Objec ...

Modifying Row Color in Bootstrap 3: A Step-by-Step Guide

I'm trying to customize the background color of alternating rows in a Bootstrap 3 grid. I attempted to use CSS and add it to the class within the div, but unfortunately, the color isn't changing as expected. Below is the CSS code I used: .row-b ...

Connecting an image to its corresponding content through hover effect

Can someone please assist me? I am trying to create a hover effect on an image with an "add to cart" link similar to what is shown here: I seem to be having trouble with the code, could you provide some guidance? .hunderter { background: url(http ...

Position this menu in the top left corner using HTML and CSS

Is there a way to position the vertical menu completely in the top-left corner without any margin? I've set all margins to 0 but there is still about 2px of space. Any ideas on how to fix this? Thank you in advance! ...

Using a MySQL statement within a conditional statement

Looking to modify this code to display different information based on the values retrieved, here is the current code: $sql_doublecheck = mysql_query("SELECT * FROM adminpage WHERE setting='main' AND close_site='1'"); $doublecheck = mys ...

What is causing the div element to act as a container?

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f7fafae1e6e1e7f4e5d5a1bba3bba5">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-B0v ...

What could be causing the issues with the compatibility of <input type="text" and flex properties?

I'm having an issue where the search box expands in size when I apply display:flex in my CSS. Can someone explain why this happens and offer a solution to return the search box to its normal height? Additionally, I would like the search bar and the se ...