Conceal the scroll bar while the page preloader is active

Is there a way to hide the scroll bar while the preloader is loading on a webpage? I want to prevent users from scrolling until the preloader disappears. I have tried using CSS and setting the body overflow to hidden, but it's not working as expected. The preloader effect I am using involves canvas. Can someone guide me in the right direction?

/* Preloader Effect */
var noise = function(){
//const noise = () => {
    var canvas, ctx;

    var wWidth, wHeight;

    var noiseData = [];
    var frame = 0;

    var loopTimeout;


    // Create Noise
    const createNoise = function() {
        const idata = ctx.createImageData(wWidth, wHeight);
        const buffer32 = new Uint32Array(idata.data.buffer);
        const len = buffer32.length;

        for (var i = 0; i < len; i++) {
            if (Math.random() < 0.5) {
                buffer32[i] = 0xff000000;
            }
        }

        noiseData.push(idata);
    };


    // Play Noise
    const paintNoise = function() {
        if (frame === 9) {
            frame = 0;
        } else {
            frame++;
        }

        ctx.putImageData(noiseData[frame], 0, 0);
    };


    // Loop
    const loop = function() {
        paintNoise(frame);

        loopTimeout = window.setTimeout(function() {
            window.requestAnimationFrame(loop);
        }, (1000 / 25));
    };


    // Setup
    const setup = function() {
        wWidth = window.innerWidth;
        wHeight = window.innerHeight;

        canvas.width = wWidth;
        canvas.height = wHeight;

        for (var i = 0; i < 10; i++) {
            createNoise();
        }

        loop();
    };


    // Reset
    var resizeThrottle;
    const reset = function() {
        window.addEventListener('resize', function() {
            window.clearTimeout(resizeThrottle);

            resizeThrottle = window.setTimeout(function() {
                window.clearTimeout(loopTimeout);
                setup();
            }, 200);
        }, false);
    };


    // Init
    const init = (function() {
        canvas = document.getElementById('noise');
        ctx = canvas.getContext('2d');

        setup();
    })();
};

noise();

$(document).ready(function(){
$('body').css({
  overflow: 'hidden'
});
setTimeout(function(){
  $('#preloader').fadeOut('slow', function(){
    $('body').css({
      overflow: 'auto'
    });
  });
}, 5000);
});
#preloader {
position: fixed;
height: 100vh;
width: 100%;
z-index: 5000;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #fff;
/* change if the mask should have another color then white */
z-index: 10000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="preloader">
<canvas id="noise" class="noise"></canvas>
</div>

Answer №1

Give these Codes a try and see if they work for you. I stumbled upon this on StackOverflow. Source: Disable scrolling when preload a web page

Javascript Code

$(window).load(function() {
      $(".preloader").fadeOut(1000, function() {
          $('body').removeClass('loading');
      });
    });

CSS Code

.loading {
      overflow: hidden;
      height: 100vh;
    }

    .preloader {
      background: #fff;
      position: fixed;
      text-align: center;
      bottom: 0;
      right: 0;
      left: 0;
      top: 0;
    }

    .preloader4 {
       position: absolute;
       margin: -17px 0 0 -17px;
       left: 50%;
       top: 50%;
       width:35px;
       height:35px;
       padding: 0px;
       border-radius:100%;
       border:2px solid;
       border-top-color:rgba(0,0,0, 0.65);
       border-bottom-color:rgba(0,0,0, 0.15);
       border-left-color:rgba(0,0,0, 0.65);
       border-right-color:rgba(0,0,0, 0.15);
       -webkit-animation: preloader4 0.8s linear infinite;
       animation: preloader4 0.8s linear infinite;
    }
    @keyframes preloader4 {
       from {transform: rotate(0deg);}
       to {transform: rotate(360deg);}
    }
    @-webkit-keyframes preloader4 {
       from {-webkit-transform: rotate(0deg);}
       to {-webkit-transform: rotate(360deg);}
    }

HTML Code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body class="loading">
  <div class="preloader">
    <div class="preloader4"></div>
  </div>

//More code here

</body>

Answer №2

To achieve the desired effect, make sure to apply overflow: hidden and height: 100vh on both the body and html elements.

/* Implementing Preloader Effect */
var noise = function(){
//const noise = () => {
    var canvas, ctx;

    var wWidth, wHeight;

    var noiseData = [];
    var frame = 0;

    var loopTimeout;


    // Generating Noise
    const createNoise = function() {
        const idata = ctx.createImageData(wWidth, wHeight);
        const buffer32 = new Uint32Array(idata.data.buffer);
        const len = buffer32.length;

        for (var i = 0; i < len; i++) {
            if (Math.random() < 0.5) {
                buffer32[i] = 0xff000000;
            }
        }

        noiseData.push(idata);
    };


    // Display Noise
    const paintNoise = function() {
        if (frame === 9) {
            frame = 0;
        } else {
            frame++;
        }

        ctx.putImageData(noiseData[frame], 0, 0);
    };


    // Animation Loop
    const loop = function() {
        paintNoise(frame);

        loopTimeout = window.setTimeout(function() {
            window.requestAnimationFrame(loop);
        }, (1000 / 25));
    };


    // Configuration
    const setup = function() {
        wWidth = window.innerWidth;
        wHeight = window.innerHeight;

        canvas.width = wWidth;
        canvas.height = wHeight;

        for (var i = 0; i < 10; i++) {
            createNoise();
        }

        loop();
    };


    // Resetting
    var resizeThrottle;
    const reset = function() {
        window.addEventListener('resize', function() {
            window.clearTimeout(resizeThrottle);

            resizeThrottle = window.setTimeout(function() {
                window.clearTimeout(loopTimeout);
                setup();
            }, 200);
        }, false);
    };


    // Initialization
    const init = (function() {
        canvas = document.getElementById('noise');
        ctx = canvas.getContext('2d');

        setup();
    })();
};

noise();

$(document).ready(function(){
$('body, html').css({
  overflow: 'hidden',
  height: '100vh'
});
setTimeout(function(){
  $('#preloader').fadeOut('slow', function(){
    $('body, html').css({
      overflow: 'auto',
      height: 'auto'
    });
  });
}, 5000);
});
#preloader {
position: fixed;
height: 100vh;
width: 100%;
z-index: 5000;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #fff;
/* change if the mask should have another color then white */
z-index: 10000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="preloader">
<canvas id="noise" class="noise"></canvas>
</div>

Answer №3

To change the position of body to fixed, then revert it back when the page finishes loading, follow this code:

document.body.style.position = "fixed";
window.addEventListener("load", () => {
    document.body.style.position = "";
    document.querySelector(".loader").style.display = "none";
});

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

A subtle background image with an overlay of a transparent RGBA gradient

Currently, I am working on designing the header of a website. My goal is to incorporate an image on the right side of the header, overlayed with a gradient color that has a certain level of transparency set using rgba values. Although the image and gradien ...

Issue with Achieving Two-Way Binding in Angular 1.5 Component when using $ctrl

I am struggling with customizing some products using a component in my index.html. Ultimately, I need to calculate the total of selected products within the main controller "planosVoz" using two-way binding on the svaTotal property in the component control ...

Ways to divide the vuetify-text-field-label into two lines

My vuetify text field has a label that is too long for mobile devices. I am wondering if there is a way to automatically wrap the text. I attempted using div and p, as shown in this codepen link <div id="app"> <v-app id="inspire ...

Quick and easy way to access json data with jquery

Need help with reading data from JSON format using jQuery. I've attempted the code below, but I'm having trouble retrieving the exact data I need. $.ajax({ url: '@Url.HttpRouteUrl("GetDistrictList", new { })', ...

Exploring the process of passing an array as a function argument from PHP to JavaScript

I am looking for assistance in passing an array as a function argument from PHP to JS. The values I need are retrieved from a database. while ($rows = pg_fetch_array($qry)) { ?> <option value="<?php echo $rows[&ap ...

Even though the Spotify API JSON response may be undefined, I am still able to log it using console.log()

Trying to utilize Spotify's Web Player API in order to retrieve the 'device_id' value has been a challenge. The documentation states that the server-side API call I am supposed to make should result in a 'json payload containing device ...

Unique Google Maps API V3 PEGMAN Customization

Can custom zoom controls and Pegman controls be styled with the same design? To add custom zoom controls, follow the instructions provided in this question's answer: <!DOCTYPE html> <html> <head> <meta name="viewport" cont ...

Identifying JavaScript Errors in a Web Page: A Guide to Cypress

Currently, I am working on creating a spec file that contains N it(s), with each it visiting a specific page within the application and returning the number of errors/warnings present. I have also shared my query here: https://github.com/cypress-io/cypres ...

Guide on dynamically applying a CSS rule to an HTML element using programming techniques

Currently working with Angular 6 and Typescript, I am facing a unique challenge. My task involves adding a specific CSS rule to the host of a component that I am currently developing. Unfortunately, applying this rule systematically is not an option. Inste ...

Stacking pictures with CSS and absolute placement

I have designed a webpage where I need to layer three images in a specific order to create a background for content placement without any movement during scrolling. Fixed positioning is not suitable for this purpose. Below is the sequence in which the imag ...

Exploring the Form's data-url Attribute

My form tag is set up like this: <form data-id="213" method="post" onsubmit="javascript: startAjax(); return false;"> <input type="submit" value="submit"> </form> When I submit the form, an ajax script runs to validate some information ...

When hovering, apply style 1 to all elements with the same id, and style 2 to the hovered element

I'm working with some user-generated divs that I want to dynamically highlight when hovered over, while simultaneously blurring the other divs. My challenge is figuring out how to change the style of the hovered div separately from all the others. Th ...

Enhance the Error class in Typescript

I have been attempting to create a custom error using my "CustomError" class to be displayed in the console instead of the generic "Error", without any success: class CustomError extends Error { constructor(message: string) { super(`Lorem "${me ...

The size of text enclosed within div elements appears distorted

Having difficulty adjusting text size within div tags, specifically when trying to set it in pixels. For example, setting font-size to 20px while maintaining a div size of 250 by 50 pixels results in stretched out text. Here's the code snippet: .NavB ...

JavaScript is reliant on the presence of the alert() function to properly function

I have a JavaScript function that performs well, except for when I remove or comment out the alert() line. This function is designed to calculate the sum of values in up to 30 fields if they are present and contain a value. Here is an example of the HTML ...

I'm looking for a way to track the progress of an ajax call. Specifically, I want to know how I

I am currently working on an AJAX call that executes a lengthy PHP script producing 20 different results. I aim to display the progress of each step within the script, such as 1/20 complete, 2/20 complete, 3/20 complete. Last updated on 29-12-2015 at 03:1 ...

Creating unique div elements with varying sizes that perfectly complement each other

I'm interested in creating a grid of divs that are randomly filled, similar to the image shown. I want them to be completed in a unique way without overlapping with each other. Is there a method to achieve this? ...

Issue with arranging cards in a grid when utilizing v-for alongside bootstrap

Just starting out with vuejs and attempting to create a grid by looping through objects using bootstrap classes. However, I'm running into an issue where the cards are not forming a grid as expected when utilizing the col classes. Below is the code f ...

Can you effectively link together AngularJS promises originating from various controllers or locations?

Attempting to explain in as much detail as possible, the configuration file config.js contains the following code snippet: .run(['$rootScope', '$location', 'UserService', 'CompanyService', function($rootScope, $loca ...

Troubleshooting script not detecting changes in form

I am currently implementing a script to detect any changes in the form fields and notify the user if there are any. However, instead of triggering the alert box as intended, a different JavaScript box is displayed. Despite my efforts, the script is not re ...