Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Code not working is js seprate file but it works when i put it in a <script>

so as the title says, i want to create a loader but the script works when i put it in the html file but i doesn’t when i put it in my sperate js file

here’s the script

var loader = document.getElementById("ld");
    window.addEventListener("load", function()
    {
      loader.style.display = "none";
    })

and here’s the html

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="Bilal el Badaoui">
<meta name="description" content="The best clothes for the best price">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>S&B Clothes</title>
    <link rel="icon" type="image/x-icon" href="logo/icons8-needle-96.png">
</head>

<body id="body">

<div class="loader" id="ld"></div>

</body>

>Solution :

This block is the problem. Change this block:

var loader = document.getElementById("ld");
    window.addEventListener("load", function()
    {
      loader.style.display = "none";
    })

to:

window.addEventListener("load", function()
{
  var loader = document.getElementById("ld");
  loader.style.display = "none";
})

Why?
You include your js script in the head of your dom. Then you have to wait if the entire dom is loaded. Because your script will start to select a element which is not loaded. For this reason you have to put your code inside the load event.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading