Tips for stopping the body from scrolling when using a Responsive menu

I am currently working on integrating the Responsive Menu plugin into a WordPress theme. However, I am facing an issue where the push-side menu causes the body to move vertically when open.

Fortunately, there is a solution available for this specific template page that works amazingly well and has produced satisfactory results.

The question: Considering the answer provided by Outsource WordPress which fixed the aforementioned page, is it possible to modify the code below in order to make it usable across various template pages such as here, similar to how it currently functions here?

I believe that `.edge-ils-item-link` and `.edge-ils-content-table` are variables, but I am unsure of how to approach and adjust them. I have attempted replacing these elements without success, suggesting that the solution may be more complex than initially thought. Additionally, elements like `edge-wrapper`, `edge-wrapper-inner`, and `wpb_wrapper` are present on all pages, indicating that modifying these common elements could potentially enhance the overall solution’s versatility.

It would also be beneficial to ensure compatibility with the latest jQuery version (currently using jQuery migrate 1.4.1) and an older version of Wordpress for functional purposes on the designated page.

.scroll-lock{position:fixed !important;}

$(document).ready(function() {
    var windowTop = 0;
    var menuOpen = 0;
    var offsetContainerList = 0;

    $('#responsive-menu-pro-button').click(function() {
        var offsetScrollList = $('.edge-ils-item-link:first').offset().top; 

        if ($('html').hasClass('scroll-lock')) {
            $('#responsive-menu-pro-container').one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend",
              function(event) {
                  if (menuOpen==0) {
                      menuOpen = 1;
                      $('html').removeClass('scroll-lock');  
                      $('.edge-ils-content-table').css('top', eval(offsetContainerList)-40+'px');
                      $('html').scrollTop(windowTop); 
                  }
                  else {   
                      menuOpen = 0;             
                  }
            });
        }
        else {                
            windowTop = $(window).scrollTop();
            offsetContainerList = $('.edge-ils-content-table').offset().top;  
            $('html').addClass('scroll-lock');      
            $('.edge-ils-content-table').css('top', -offsetScrollList + 'px'); 
        }      
    }); 
}); 

If needed, you can view a video demonstrating the issue here.

Answer №1

Alright, let's address the issue at hand:

The problem arises from the plugin applying transform: translateX(800px); to your main div. This causes all inner divs with a fixed position to lose their fixed positioning and instead become relative, hence moving them to the top.

A Simplified Solution:

Instead of delving into complex solutions like tracking user positions and intricate workarounds, why not just skip the transform and use margin-left instead?

<style>

html.responsive-menu-pro-open {
  overflow-y: hidden !important;
  padding-right: 9px;
} 

#responsive-menu-pro-container {
  position: fixed !important;
}

#responsive-menu-pro-container {
  position: fixed !important;
  transform: none !important;
  margin-left: -800px;

  transition: 2.6s ease; 
  transition-timing-function: cubic-bezier(0.96, 0, 0.13, 1); 
  transition-property: margin-left; 
}

#responsive-menu-pro-button {
  transform: none !important;
  transition: 2.6s ease !important; 
  transition-timing-function: cubic-bezier(0.96, 0, 0.13, 1) !important; 
  transition-property: margin-left !important;
}

...

</style>

By implementing the code above, you can achieve the desired functionality without using transform by simply adjusting margin-left.

Notes - Due to the complexity of your page layout with multiple fixed elements nested within each other, you may need to alter margins on different elements. Simplifying your layout or utilizing the plugin's built-in transform feature could streamline this process.

This solution may be specific to the provided example page; customization may be required for other pages. Consolidating all pages under a single wrapper div could facilitate uniform application of the code snippet across pages.

In Conclusion - Addressing the plugin issues related to page layout is crucial. Contacting the developers for tailored assistance based on your theme specifics might yield a more effective resolution than the workaround presented here. Understandably, without access to your code, this workaround offers the best alternative without resorting to scroll manipulation.

Answer №2

Upon inspection, I discovered that the class "scroll-lock" is not being added to the html element on your main page labeled "scroll-lock", but it is successfully added on the "ilinks-push" page. As a result, the condition checking for this class will never evaluate to true on your subpages. To address this issue, I modified the code to target the intended class named "responsive-menu-pro-open."

Furthermore, in order to ensure functionality across all subpages, it is crucial to grasp the logic implemented in the current codebase. I made some adjustments and included explanatory comments to enhance clarity:

$(document).ready(function() {
    var windowTop = 0;

    $('#responsive-menu-pro-button').click(function() {

        /* check if there is an ils item link */
        if ( $('.edge-ils-item-link')[0] ) {
            /* store the space above the element in a variable */
            var offsetScrollList = $('.edge-ils-item-link:first').offset().top;
        }

        /****** Menu expansion *****/

        if ($('html').hasClass('responsive-menu-pro-open')) {

            /* scroll to the top of the page */
            windowTop = $(window).scrollTop(); 
            /* add the scroll-lock class */
            $('html').addClass('scroll-lock');
            
            /* check if there is an ils item link */
            if ( $('.edge-ils-item-link')[0] ) {
                /* restore the saved space to maintain original scroll position */      
                $('.edge-ils-content-table').css('top', -offsetScrollList + 'px'); 
            }
            
        }

        /****** Menu collapse ******/

        else { 
            $('html').removeClass('scroll-lock');

            /* check if there is an ils item link */
            if ( $('.edge-ils-item-link')[0] ) {
                /* utilize the saved space to reset the scroll position */
                $('.edge-ils-content-table').css('top', -offsetScrollList +'px');
            }

            $('html').scrollTop(windowTop);
        }

    }); 
}); 

You may have noticed sections where "check if there is an ils item link" is mentioned.

These are likely the segments that differ on your subpages.

By utilizing .offset().top, we capture the space above elements. However, this approach only functions effectively if elements with the ".edge-ils-item-link" class are present, hence why such implementation is enclosed within if statements.

In the current codebase, spaces above are used to correctly position elements, creating the appearance of a blocked scroll. Identifying the correct elements necessitates knowledge of their classes.

It is essential to maintain consistency by ensuring each page employs consistent classing around the content area. This facilitates targeting elements without requiring additional conditional checks in the JavaScript code.

Alternatively, numerous if clauses could be devised to inspect page elements. For instance, in your "scroll-lock" page, the "info-field" element might enable space configuration. Nonetheless, issues arise due to its fixed positioning conflicting with the addition of the "scroll-lock" class featuring "position: fixed;".

To rectify this situation, consider adjusting content layouts across subpages to streamline problem resolution. Constantly adapting JavaScript for varied subpage structures is impractical. Attempt standardizing subpages into dual columns using flexbox—perhaps maintaining a fixed left column while allowing scrolling within a static right column. The provided details lack specifics regarding your setup, thus hindering precise recommendations.

Answer №3

To ensure that the vertical scroll is only displayed when the content exceeds the viewport height, include min-height: 100vh; in the body tag.

Currently, the height of your document pages is limited to the combined height of relatively positioned children. Please see the screenshots below for reference. https://i.sstatic.net/rokZ6.png

https://i.sstatic.net/deDS7.png

Answer №4

After reviewing the required behavior, I believe the solution is straightforward and does not need to be overcomplicated:

Upon examining the pages and script behavior, it became evident that the scroll-lock class was not added to the DOM. However, you can simply rely on the presence of the responsive-menu-pro-open class being added to the HTML element after opening the menu. By applying CSS properties to this class, such as setting its position to fixed across all dimensions, you should be able to achieve the desired outcome. Please verify.

.responsive-menu-pro-open{
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
}

I have tested this solution myself, and it worked flawlessly. Hopefully, this guidance proves helpful to you :)

Answer №5

For those facing this issue, the perfect solution lies within the Wordpress plugin you're utilizing, known as Responsive Menu. This plugin provides options for customization that can resolve the problem at hand. Personally, I have implemented it on my own website, Couv's Corner. Here are a few troubleshooting tips to consider:

  • Ensure that the plugin is up-to-date, as recent updates have made significant improvements.
  • Utilize sub-menus effectively by nesting menu items under parent categories where appropriate. Customize these settings in the "Menus" section of your admin dashboard.
  • Review your theme. Consider exploring themes like Kadence WP to potentially identify any conflicts with the current theme you are using.
  • Attempt to optimize your site's database and files, and clear cache/CDN if applicable. These steps could potentially help resolve the issue you are experiencing. I hope these suggestions prove helpful. Take some time to explore the plugin and observe how I have configured it on my personal site, and share your thoughts on it.

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 with configuring Ajax request and response

I have a specific page dedicated to generating a table using data from a query. This page solely focuses on presenting the table. My goal is to utilize jQuery/ajax to call this page and incorporate its output into a function. Below is the jQuery function ...

Exploring the realm of Angular templating and routing combined with the power

Currently, I am in the process of developing my very first Angular website that involves templating and routing. My goal is to have an image on the page that spans the entire window size minus 70 pixels. //Using Jquery (This particular section functions ...

Sorting arrays in ES5 with the sort() method

In my array, I have multiple objects with a 'time' property that stores date strings. elements = [ {time: "2013-03-01T10:46:11Z"}, {time: "2013-03-03T10:46:11Z"}, {time: "2013-03-02T10:46:11Z"} ] My goal is to ...

Dynamic buffer geometry featuring morph attributes fails to refresh the shadow animation

Recently, I revamped the MD2 code within the library to utilize THREE.BufferGeometry instead of THREE.Geometry, resulting in a significant reduction in memory usage. The process involved converting the model to THREE.BufferGeometry post-loading and making ...

Writing to the database right before exiting the webpage

A technique for detecting when a user leaves a page. const captureLeavingPage = () => { window.onbeforeunload = function (evt) { var message = "Are you sure you want to leave?"; if (typeof evt == 'undefined') { evt = window.ev ...

Publishing Your App on the Android Market with PhoneGap

Seeking a comprehensive PhoneGap tutorial that covers app publishing, especially struggling with successful app deployment. Currently experienced in HTML, CSS, and JavaScript. Any tips or advice would be greatly appreciated, thank you! I have a good gras ...

Moving the webpage into the realm of mobile and tablet devices

Over the next few weeks, I will be working on transitioning my website content to have both a mobile and tablet version. During this process, I have some questions: What is the best way to redirect users to the correct site based on their device/browse ...

Getting information from Button-Group using JavaScript

I have a similar question that was previously asked here: Get Data-Values from Selected Bootstrap Button Group (Checkboxes) and Assign to Input However, my structure is different because I need a group of buttons with the option to select more than one. ...

Is it possible to update the state of the Context API within a JavaScript class?

I am working on a Bluetooth class and listener method. My goal is to update the state in the Bluetooth class and then display it in a functional component. JavaScript Class import React, { Component } from "react"; import { MySampleContext } fro ...

Header Logo centered at the top

I am using a Bootstrap 4 navbar where the nav-brand is centered on a computer window, but shifts to a dropdown when expanded on mobile. Is there a way to keep the brand fixed at the top and center? Here is my navbar code in HTML: <nav class="navba ...

Determine the true size of a string, similar to how we measure with a ruler

My goal is to determine the amount of time it takes for the caret to move from the beginning to the end of a string. Explanation: Consider this string "" in the following code snippet: http://jsfiddle.net/RFuQ3/ If you place the caret before the first ...

Success function in AJAX triggered when no JSON data is returned

Despite its simplicity, I'm having trouble getting this right. I'm utilizing jQuery/AJAX to fetch data (in the form of JSON) from my database. Upon successful retrieval, I have a function to display the data. While this works as expected, I now a ...

What advantages does using `prestart` offer compared to `&&` in a command within `package.json`?

I believe the title speaks for itself, but let's dive in: What advantages does using the pre-script of npm package.json, like prestart, have over simply combining commands with && in the start script? { prestart: "parcel build", start "n ...

Discover how to utilize images encoded in base64 format within webhook embeds on Discord

Can someone help me with inserting an image into a Discord embed using a webhook? I have the image saved as a base64 string obtained from a database. However, my attempts so far have only resulted in an empty embed. https://i.sstatic.net/CVs4j.png const d ...

Interactive Image Hover - CSS and JQuery

After finding a tutorial on creating an image-hover plugin using jQuery and CSS (), I successfully implemented it on my website. However, I encountered an issue with responsiveness as I would like the images to scale according to my 960gs grid system. Yo ...

Creating Blurry Text Effects in HTML (Step-by-Step Tutorial)

I have a basic text that is centered inside the canvas. However, it appears blurry and unattractive. Can anyone suggest how to enhance its appearance? // Populate the signature canvas with data var canvas = document.getElementById("signatureCanvas"); v ...

Review Limited Screen Size for a Smartphone Website

I have been working on optimizing a mobile website and I utilized CSS to adjust the layout design for screen widths between 150px and 480px. However, during testing on an actual phone, the desktop layout is appearing instead of the custom layout set with C ...

Employ the 'strictNullChecks' flag for a single function or method

I am working with the following method implementation: remove(node: SortedQueueNode<V, K>) : SortedQueueNode<V, K>{ // ... return node.parent; } In this function, there are several points where it returns a value, and I want to en ...

Guide to using react-router for redirection and displaying messages

Is there a way in React to redirect after a successful login with a success message displayed on another component? I previously used flash messages, but they didn't integrate well with react-router and caused full page refreshes. Now that I am using ...

What is the best way to conceal a div element on a Razor Page depending on the user's input?

How can I display the state field only when the user selects United States in the country field, and hide it otherwise? Here is the code snippet from my cshtml page: <div class="form-group col-sm-4 mt-4"> <label asp-for="Form.Co ...