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

The $ symbol is not recognized in this context [jQuery, MasterPage, UserControl, Shared/static Event handler, external javascript]

Unfortunately, I am facing a challenge in replicating this issue outside of my application. If anyone is willing to assist, I have a VS2012 project that can be shared for further investigation. The functionality works fine in isolation but fails in a large ...

Show the final element in a list in a new and innovative style

How can I style the last item of a list differently? The issue is with the display of the last item in the list, which may go out of bounds on smaller screens. To ensure proper display, the list item "Argenti" needs to be shown in a single column. To ach ...

I encountered an issue with the onclick event in JavaScript

I have been struggling with an issue for some time now and I just can't seem to figure out what I am doing wrong. Here's the problem - when I click on a link on my website, a calculator should pop up. Then, when I click the off button on the calc ...

What is the best way to connect the "areaName" with the <TextBox> attributes value="" and onChange=""?

After calling an API and mapping the array, I have successfully bound the data on <TableCell> {this.state.allArea.map((allArea, i) => ( <TableRow > <TableCell >{allArea.areaName}</TableCe ...

The submit function in jQuery is failing to send the form data when used with input types of submit

I need help submitting a form with two different submit buttons. Below is the HTML code: <form enctype="multipart/form-data" id ="type-1" accept-charset="UTF-8" action="process_upload.php" method="post" onsubmit="return Genome_upload_validation()" > ...

exploring div element(s) with jQuery

My HTML page contains multiple div elements in the body. I have also included buttons with associated click functions in jQuery to change the background-color of a div element based on the button pressed. However, I'm facing an issue at the 'term ...

The scope's attribute is present, but the variable within the scope's attribute is not

Currently, I am delving into angularJS development, but encountering a perplexing issue. I am attempting to format a JSON into a table with intricate rules. The JSON structure currently is as follows: { "id":"test", "title":"Test Sample", "de ...

I encounter Error 406 and CORS issues when making API calls

I am currently engaged in a project aimed at helping my employer keep track of shipping loads, customers, carriers, and locations. The frontend is built using a react app that enables users to input information regarding loads, customers, etc. On the backe ...

Avoid displaying null values in SELECT and GET operations when using node-postgres

Within my Express API functionality, I aim to offer the client flexibility in providing their contact details, namely phone number or website address, with the option of leaving them blank. The SELECT queries in use are as follows: -- Retrieve all users S ...

How can we target every nth child element universally?

I am working with an HTML structure that has a specific layout, and I need to target all odd <span> elements globally without considering their parent elements. Is there a way to style 1, 3, 5, 7, 9 in red color? I attempted to use :nth-child(odd) b ...

Tips for retrieving the tenth document in Firestore Query using JavaScript

Specifically, a selection of the arranged files. Here's my thought, although I know it can be improved: firestore().collection("queue").orderBy("order_id", "asc").limit(3,5) If anyone has a better solution, I would appre ...

Experimenting with NGXS selectors: A comprehensive guide

Hey there, I am currently utilizing the NGXS state management library in my application. I have a selector set up like this and everything seems to be functioning correctly. However, while testing the app, I encountered the following error message: "PrintI ...

Dimensions of CSS Buttons

On my screen, I have 3 buttons with varying sizes determined by their padding. As the text wraps within each button, they adjust in height accordingly. However, the issue arises when the buttons end up being different heights. Instead of setting a specific ...

The functionality for determining whether the value isset as 'Yes' or 'No' is not functioning properly in my PHP form

I'm currently working on creating a combined 'Order Calculator / Order Form' using one php form. The calculator part of the form is functioning perfectly and accurately calculates the total for all 5 order options both on the live page and i ...

The array is failing to pass through ajax requests

Here is the JavaScript code snippet for making an AJAX call. In this scenario, the code variable is used to store a C program code and then pass it on to the compiler.php page. function insert(){ var code = document.getElementById("file_cont").val ...

A step-by-step guide on ensuring mandatory completion of all input fields prior to form submission

I'm new to JavaScript and I need some help. Currently, I am trying to implement input field validation using pure JavaScript for a form. However, I am facing an issue where the "Required" message only appears next to the last name input. What I want ...

In JavaScript, the "this" keyword points to a different object

Here is a script that needs attention: Bla = function() { this.prop = 123; } Bla.prototype.yay = function() { console.log(this,this.prop); } X = new Bla(); $(document).ready(X.yay); // output: #document undefined --> why? $(document).ready(functio ...

The horizontal overflow is malfunctioning, resulting in only a limited number of columns being visible on the screen

I am facing an issue with the CSS for my table. Despite using overflow-x: scroll, only half of the columns are being displayed on the screen out of the 15 total columns. Can anyone provide assistance with this problem? .table { font-family: Roboto,"He ...

Is it possible to obtain the socket.id of a user immediately upon their connection?

Does anyone know how I can send a personalized message to a user when they connect, without broadcasting it to everyone else? I'd like to use their socket ID with the code io.to(theirSocketID).emit('chat message', 'Welcome');, but ...

Create a new build for testing and debugging using create-react-app

Currently, I am in the process of developing a web application that utilizes a React frontend and is powered by a golang api layer. Although I do not have extensive experience with Javascript, I find myself struggling with the Node build system. I am loo ...