Prevent body scrolling when modal view is activated

As I work on developing this website, I have encountered an issue. Upon clicking a link located at the far right end of the second row in the header, a modal window appears with embedded YouTube videos.

The problem arises when scrolling through the modal: the BODY also scrolls, and I am looking to prevent that from happening. Can anyone offer guidance on how to address this issue?

Any help would be greatly appreciated! Thank you for taking the time to assist.

Answer №1

To implement the desired functionality, update your CSS with the following rule:

body.modal-open {
    overflow: hidden;
}

Additionally, utilize jQuery to dynamically add the .modal-open class to the <body> element when the modal is open, and remove it when the modal is closed.

$("#myModal").on("show", function () {
  $("body").addClass("modal-open");
}).on("hidden", function () {
  $("body").removeClass("modal-open")
});

Answer №2

Instead of following the usual method of applying fixed positioning to the "BODY" tag when a modal is opened, I discovered a different approach that worked better. By setting overflow hidden on the html tag rather than the body tag, we can eliminate the need for fixed positioning and ensure that the document remains where it was before the modal was opened.

To implement this fix, simply add the following code:

function openModal(){
   $("html").css({"overflow-y":"hidden"})
   // Add your modal box function here...
}

By creating a CSS class and toggling it on HTML when opening or closing the modal box, you can easily apply this solution without any hassle. This method has successfully resolved the issue for me.

Answer №3

If you want to prevent a DOM element from scrolling, you can achieve this by applying CSS properties like overflow hidden and position fixed. Take a look at the example below:

.disable-scroll {
    /* disable both x and y axis scrollbar */
    overflow: hidden;

    /* disable only x-axis scrollbar */
    overflow-x: hidden;

    /* disable only y-axis scrollbar */
    overflow-y: hidden;

    /* stop scrolling */
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;

    /* OPTIONAL: make the dom element not clickable */
    pointer-events: none;
}

Answer №4

To prevent scrolling, I suggest applying the CSS rule overflow: hidden; to both the html and body tags.

However, if your modal contains a lot of content, it's best to use a scrollable container for the modal. For an example, check out this link:

Answer №5

Just using overflow: hidden; isn't enough for browsers like Chrome and Firefox. A solution is to utilize position: fixed;, but this can cause the screen to jump when closing the modal.

To fully hide the scrollbar in both Chrome and FF, you can try:

.modal-open {
  -moz-appearance: menuimage;
}

.modal-open::-webkit-scrollbar {
   width: 0 !important;
}

Keep in mind that while this disables the scrollbar, users may still be able to scroll using keypresses, text selection, or touch gestures.

An alternative approach is to set the height of elements inside the body to zero, such as all divs:

.modal-open div {
  height: 0px;
}

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

What causes an "Undefined index" error in jQuery when making AJAX requests?

Whenever I make an AJAX request in my main.js file, I encounter the following error message: Undefined index: id in sqlinfo.php on line 13 I am puzzled because I believe that I am populating the request object correctly. What's even more perplexing i ...

Tips for customization: Altering HTML table borders and column widths

I am looking to update the appearance of an HTML table. Currently, it looks like this: https://i.sstatic.net/pueyW.png Here is the code snippet: <div className="student-schedule"> <table className="student-calendar-table" ...

JavaScript: Creating a new entry in a key-value paired array

I am in the process of creating a dynamic menu for use with jQuery contextMenu. I have encountered an issue when trying to add a new element, as it keeps showing the error message 'undefined is not a function'. The menu functions correctly witho ...

Transferring a method through two layers of hierarchy

I'm currently working on a fun little game project, but I've hit a roadblock when it comes to passing a particular method down to its grandchildren components. Despite finding similar discussions on this topic, none seem to address my specific qu ...

Using @use in Bootstrap version 5 instead of @import for customizing your styles

Looking for a solution to utilize @use instead of @import in order to import all variables from my _custom.scss partial into the styles.scss sass file. However, facing an issue where @use is not overriding the variables as expected. Any suggestions for res ...

Angular Elements - Additional Attribute Bindings

My goal is to create a series of versatile components (angular 1.5) with various optional bindings that can be utilized in multiple applications. I am concerned about the potential creation of unnecessary watchers for an application that does not utilize ...

How can you incorporate a horizontal line beneath your text, similar to the one shown in the

https://i.sstatic.net/OzMVr.jpg I have a code snippet that needs a horizontal border similar to the one shown in the image <section class="about"> <div class="container"> <h1 class="text-center"> ...

Using the getAttribute method in Edge with JavaScript

My goal is to dynamically load videos on the page after it has fully loaded. I have a script that successfully works in Firefox and Chrome, but I encounter errors when using Edge/IE. The specific error message I receive is SCRIPT5007: Unable to get propert ...

Enable direct download from external servers

I'm in search of a way to prompt a download (by right-clicking and selecting "save as") for both mp4 and flv files. The challenge is that these files are not hosted on my server, they are direct links from external websites. I have tried using .htacce ...

Leveraging the post method in Ajax along with a Perl script and passing parameters

I am struggling to utilize the POST method in XMLHTTPRequest by invoking a Perl script with parameters. Despite confirming the validity of these variables (uName, uProject, etc.), and verifying that write.pl functions properly when parameters are manuall ...

What is the reason behind Visual Studio intellisense not displaying the methods of XMLHttpRequest objects?

Why am I unable to access the open and send methods of the XMLHttpRequest object in Visual Studio's Intellisense? var httprequest = new XMLHttpRequest(); httprequest. I cannot see the methods in Intellisense after the dot. ...

Is there a way to reverse the process of Date.parse?

After converting a date to a number with the following code: Date.parse(doc.createdAt); I receive this result: 1576699528000 It seems like the number becomes a string when passed from the server to the front end and back to the server. How can I conver ...

Jquery attribute not functioning correctly when setting the 'required' property for checkboxes

One of the challenges I am facing is trying to toggle a text box on a checkbox's click event. While I have achieved success in this aspect, my issue lies in changing the checkbox's required attribute as well. Below is the code that successfully ...

What is the method to integrate PHP with HTML code?

Apologies if this question has been asked before, but I have not found anyone with the same query as mine. I am new to HTML and PHP, and I am looking to enhance my skills by creating a registration form and storing all the data in a MySQL database using XA ...

I'm having trouble accessing a specific field within my Django ManyToMany Relationship

In my Django Models, I have a model named announcement. This model has a message field where I can input the content of the message, along with a student_id field which specifies the receiver of the message. To send messages to specific students, I am usin ...

JavaScript: Launching the current page in a new tab or window

Is it feasible to open a new window or tab from the existing HTML page? Absolutely, I am referring to the current HTML page itself. Not triggered by an external call like this: window.open('page.html', '_blank'); Possible through Jav ...

Enhance Website Functionality with Dynamic Tables and Spreadsheet Features

Currently, I need to incorporate spreadsheet-like functions into a table on my website. Initially, I explored KendoUI but realized it might not be within my budget constraints. Is there a more affordable alternative available? Key features I require inclu ...

Is there a bug in Firefox when using rotate3d to transition from -90 degrees to -180 degrees

Currently in the process of developing a 3D content slider jQuery plugin and encountering an unusual issue with Firefox. The rotation seems to be behaving unpredictably, rotating from -90deg to -180deg through 270deg in the opposite direction. While I unde ...

Router outlet fails to load identical child component

Currently, I am working on developing a file upload interface with both grid and list views for the files. These views are separate components under a shared parent Preview component. Surprisingly, the TypeScript files for both the grid and list views are ...

I am having trouble retrieving the array value from the response sent by my server

After receiving a dictionary from my server, when I try to access the values using the following code: {"filters":{ "Facture": [ "Магма (Тычок)", "Тонкий кирпич", "Гладк ...