Utilizing the CSS 'overflow: hidden' property and jQuery to restrict users from scrolling during a loading page

OBJECTIVE

I aim to restrict the user from scrolling while the page is loading.

ISSUE

The snippet of code provided successfully prevents the user from scrolling during the additional 2 seconds of the loader animation:

$('body').toggleClass('hidden');

.hidden {
    overflow: hidden !important;
}

However, it only functions to prevent scrolling for the duration of the loader animation.

EFFORTS MADE

The approach taken was inspired by this specific query on Stack Overflow (How to show Page Loading div until the page has finished loading).

$('body').append('<div style="" id="loadingDiv"><div class="loader"></div></div>');

$(window).on('load', function() {
  $( "#loadingDiv" ).show();
  setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
  $('body').toggleClass('hidden');
});

function removeLoader() {
  $("#loadingDiv").fadeOut(1500, function() {
    // fadeOut complete. Remove the loading div
    $("#loadingDiv").hide(); 
    $('body').toggleClass('hidden');
  });
}

SUMMARY

The main goal is to prohibit the user from scrolling throughout the entire loading process - both while the page loads and for the additional two seconds of the loading animation.

UPDATE

Refer to the following snippet for a clearer demonstration of the effect:

  $('body').append('<div style="" id="loadingDiv"><div class="loader"></div></div>');

  $(window).on('load', function() {
    $( "#loadingDiv" ).show();
    setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
    $('body').toggleClass('hidden');
  });

  function removeLoader() {
    $("#loadingDiv").fadeOut(1500, function() {
      // fadeOut complete. Remove the loading div
      $("#loadingDiv").hide(); 
      $('body').toggleClass('hidden');
    });
  }
.hidden {
      overflow: hidden;
    }

    .loader,
    .loader:before,
    .loader:after {
      border-radius: 50%;
      width: 1.5em;
      height: 1.5em;
      -webkit-animation-fill-mode: both;
      animation-fill-mode: both;
      -webkit-animation: load7 1.8s infinite ease-in-out;
      animation: load7 1.8s infinite ease-in-out;
    }

    /* Additional CSS properties */

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>My Custom Loader</h2>
  <img src="#" alt="">
  <img src="#" alt="">
  <img src="#" alt="">
  <img src="#" alt="">
  <img src="#" alt="">

Answer №1

If you are persistent, try using this method:

$(document).ready(function(){

    $('body').addClass('loader');
    
    $(window).on('load', function() {
      setTimeout(function(){$('body').removeClass('loader');}, 2000);

    });
    
});
body{
    width: 100%;height: 500px;background: red;overflow: auto;
}
.loader{
    overflow: hidden !important;width: 100%;height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <h1>Body</h1>
</body>
</html>

Answer №2

Don't worry about the overflow and hiding the body. Instead, prevent scrolling before the body tag by using window.scrollTo(0,0), and then allow scrolling again in the load event by removing that event handler.

<!DOCTYPE html>
<html>
<head>
  <title>Disable Scroll Until Page is Loaded</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
    // Disable scrolling initially
    $(window).on("scroll", preventScroll);
    
    // When the window has finished loading...
    $(window).on("load", function(){ 
      // Wait for an additional 2 seconds...
      setTimeout(function(){
        // Re-enable scrolling by removing the previous 
        // event handler that disabled it.
        $(window).off("scroll", preventScroll);
        $("#loadingDiv").fadeOut(1500); // fade out the loading image
      }, 2000);
    });
    
    function preventScroll(){
      window.scrollTo(0, 0); // Effectively prevents scrolling
    }

  </script>
</head>
<body>
  <img id="loadingDiv" src="https://media3.giphy.com/media/52qtwCtj9OLTi/giphy.gif">
  
Lorem ipsum dolor sit amet, per et quas tation dissentias, ad usu illud efficiendi scribentur. Vim at ullum elitr, labores evertitur eum eu, vim urbanitas moderatius an.... (continues with lorem ipsum text)

</body>
</html>

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

An unexpected issue occurred during runtime, specifically a TypeError stating that the function posts.map is not

Currently, I am diving into the world of nextjs and decided to follow a tutorial on building a Reddit clone that I stumbled upon on Youtube. However, I encountered a persistent issue: posts.map is not a function I would appreciate any assistance you can o ...

What factors cause variations in script behavior related to the DOM across different browsers?

When looking at the code below, it's evident that its behavior can vary depending on the browser being used. It appears that there are instances where the DOM is not fully loaded despite using $(document).ready or similar checks. In Firefox, the "els ...

Creating an interactive time selection tool with two dropdown lists that are dependent on each other using HTML and JavaScript

Hi everyone, I am new to JavaScript. I am currently working on creating two dropdown lists, one for 'Start Time' and another for 'End Time'. These dropdown lists will display hours in a 24-hour format with intervals of 30 minutes. In t ...

How can I extract the page's output using JQuery?

Being a rookie in this area, I am eager to learn how to extract specific content from a page using AJAX in JQuery. Currently, I have been able to fetch the data of a page and display it as text: $.ajax({ type: "POST", url: "myfile.html", su ...

JavaScript doesn't automatically redirect after receiving a response

Hey there, I'm attempting to implement a redirect upon receiving a response from an ajax request. However, it seems that the windows.href.location doesn't execute the redirect until the PHP background process finishes processing. Check out my cod ...

Utilize the Jest moduleNameMapper for locating files: "resolver": undefined

Among the various files I have, there is a text file located in the component directory within the path: src/components/text Despite this, Jest is unable to locate the file when utilizing the webpack alias import Text from "components/text"; I ...

Using jQuery to create a Select All Checkbox that toggles a specific class

I have come across similar examples in the past, but I have been unable to make it work as intended. The examples I found only use standard checkboxes. I attempted to customize the checkbox using a sprite sheet by applying a class, but I am struggling to a ...

Change the location of an HTML element within the page structure

Let's consider having 3 elements like this: <h1>Hello</h1> <p>hello</p> <h1>Hello</h1> I am looking to remove the second <h1> as I only want it to appear once on the page. However, I would like to have flexib ...

Is it possible to execute a controller function only when the textarea has completely loaded?

My current setup includes a textarea as shown below: <textarea rows="3" maxlength="144" ng-maxlength="144" type="text" name="testPost" id="testPost_{{item.id}}" ng-init="focusText('testPost', item.id)" ng-model=" ...

Tips for including the % symbol in the Y-axis labels on a HighChart graph

I am attempting to incorporate the % symbol after the value of 100 or -100 on the yAxis in the chart shown above. I made an attempt to add the % symbols as follows: quotes.data.frequency_counts[i].negative = Math.round(negative * -1)+'%'; quote ...

Encountering issues with the functionality of the MUI Select component, causing the application to crash during

The issue has been successfully resolved I have been in the process of constructing a modal that includes a form and incorporating the MUI Select component. However, upon opening the modal, the application encounters an error; removing the Select componen ...

I am trying to access the serial number data from an array of objects in ReactJS. Can anyone guide me

Is there a way to extract data from an array of objects, such as getting the serial number in ReactJS? In my current code snippet, I have an array called "number" with values [1, 2, 3]. My goal is to retrieve and display these numbers as a string like th ...

Having trouble implementing String.prototype in my factory

Currently, I am working on incorporating a function mentioned in this answer. String.prototype.supplant = function (o) { return this.replace(/{([^{}]*)}/g, function (a, b) { var r = o[b]; return typeof r === 's ...

Is there a way to make a server call in Nodejs Express without using ajax or refreshing the page?

Currently, I am in the process of implementing MongoDB save functionality by submitting a form. My goal is to showcase the results obtained from the server without having to refresh the page. While I can accomplish this using $.(ajax), it presents a limita ...

When the parent component in React JS rerenders, the props are not automatically passed down to the child

I have come across similar questions in the past, but I have not found any answers that directly address the issue I am facing in my scenario. In my case, there is a parent component that passes a property to a child component's state. Depending on t ...

What is the best way to make sure an if statement using window.location.pathname in JavaScript/jQuery does not consider anything beyond the pathname?

I need to create a redirect from the URL "http://www.example.com/womens-collection/ceramic" to "http://www.example.com/the-ceramic". The code I am using is shown below: if(window.location.pathname == "/womens-collection/ceramic") { //alert("worked") ...

Creating personalized components - a step-by-step guide

I'm looking to customize the appearance of the snackbar background, buttons, and other elements in my Material UI project. As a newcomer to Material UI, I'm unsure if I'm taking the correct approach with this code snippet: const styles = { ...

extract the key identifier from the JSON reply

My JSON ResponseData example for form0 is provided below: { "MaterialType": "camera", "AssetID": 202773, "forms": [ { "release": "asyncCmd/accessCameraMulti", "action": "rest/Asset/202773/cameraAccessMultiple", ...

Require assistance with refreshing the index for the chosen row

I have encountered a problem while attempting to manipulate table rows using Javascript. Adding new rows works fine, but deleting rows presents an issue. Specifically, the delete function fails if the first row or a row in the middle is deleted (the live ...

Am I implementing the Vue.JS onChange function correctly?

After selecting an option from mod_accs_Role_ID, how can I display the corresponding data stored in the database based on that selection? For example, if I select 1 in mod_accs_Role_ID, then the role_Name 'Hello' should be displayed. <div clas ...