The code seems to be malfunctioning in a separate JS file, but oddly enough, it functions properly when placed within a <script> tag

I am trying to create a loader, but I have encountered an issue where the script works when placed directly in the HTML file, but not when it is in a separate JavaScript file.

Here is the script:

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

And here is the corresponding HTML code:

<!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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2a0adadb6b1b6b0a3b282f7ecf0ecf1">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="17757878636463657667572239253924">[email protected]</a>/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>

Answer №1

It seems like there's an issue with this block of code. Let's make a small tweak:

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

Here's why this change is necessary: You have your JavaScript code in the head section of your HTML document. This means that it may execute before the entire DOM has finished loading. By moving your code inside the load event listener, you ensure that the element you are trying to select is available before you attempt any operations on it.

Answer №2

When reading the code, it is important to follow the sequence from top to bottom. Initially, the script is read without seeing the "ld" id because the script comes before the body tag. To ensure that the script can access items within the body, it should be placed after the div tag. Therefore, it is recommended to place the script at the end of the body section.

    <!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">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e4c41415a5d5a5c4f5e6e1b001c001d">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fe9c91918a8d8a8c9f8ebecbd0ccd0cd">[email protected]</a>/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>

<script src="script.js"></script>
</body>

P.S. apologies for any English mistakes)

Answer №3

If you're experiencing difficulties with linking to your external JavaScript file, why not try inserting the code snippet below to see if it works? Additionally, could you confirm whether the JavaScript file is located in the same directory as your HTML file or in a separate directory? If both files are in the same directory, you should see a "hello world" message.

alert('hello world')
var loader = document.getElementById("ld");
    window.addEventListener("load", function()
    {
      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

Retrieve the 'id' value located within the 'img' tag of HTML code by utilizing Beautiful Soup in Python

Given the following code snippet: id_image = soup.find_all("img")[2] print(id_image) The result is: <img id="nexperts-logo" src="images/nexperts.png"/> I am trying to extract and print only the id value, which is ...

The hyperlink functionality is disabled because Javascript is set to return false

JS Fiddle Example When using the 'FOO' and 'BOO' items in the navigation bar to open dropdown boxes, I have implemented a code that closes them when a click event occurs outside. This code has been working fine as shown below: $(docum ...

Cannot add padding to the DIV element

Here is some HTML and CSS code that I've provided. .x{ border-bottom: 1px solid #000; } .y { border-bottom: 1px solid #000; } .z li{ display: inline; padding-top: 50px; } <div class="x"> <br> <br> <b ...

Building a straightforward expandable/collapsible tree view with AngularJS by utilizing a particular data format

Seeking a tree view control that displays as follows: http://plnkr.co/edit/JAIyolmqPqO9KsynSiZp?p=preview +Parent child +Parent child child child child +Parent child child child child child chil ...

Converting text/plain form data to JSON using Node.js - step by step guide

I am currently working on a Node.js application to execute a POST call to an API for placing an order. However, the data I receive in our app is in text/plain format and not JSON. This is the current format of the data: TypeOrder=buy Coin=BTC AmountCoin= ...

What advantages and disadvantages come with using timeouts versus using countdowns in conjunction with an asynchronous content loading call in JavaScript/jQuery?

It seems to me that I may be overcomplicating things with the recursive approach. Wait for 2 seconds before loading the first set of modules: function loadFirstSet() { $('[data-content]:not(.loaded)').each( function() { $(this).load($(thi ...

What is the procedure for renaming an item within a basic array in Angular?

I am working on a project in Angular and have constructed an array. I am now looking to change the name of one of the items in this array. While I have figured out how to rename keys in an array, I'm still unsure about how to do so for its values. ...

Upon registration, the user's information is successfully stored in the mongoDB database, even if the selected "username" is already in

I am currently working on a web application using the MERN stack. When registering a user with an existing email either through Postman or the front-end form, the user is not added to the database. The same logic is applied to check if the chosen username ...

What is the best way to place a semi-transparent black overlay on an image?

<html> <head> <style> #contain_main {background-color:black; width:100%; height:auto;} #main {width:100%; height:700px; background-image:url("https://www.sappun.co.kr/shopimages ...

Encountering an issue with Angular 5.2 application build on VSTS build server: Running into "CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory" error

Out of nowhere, the builds began failing with the following error : 2019-01-03T12:57:22.2223175Z EXEC : FATAL error : CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory error MSB3073: The command "node node_modules/webpack/bin/w ...

React Error: The property 'i' cannot be read as it is undefined

I am encountering an issue with my code: class Albs extends React.Component{ constructor(props){ super(props); this.state = { i: 0, anh: this.props.hinhanh[this.state.i] }; var hinhanh = ["1.png", "2.png", "3.png"]; this. ...

Using Jquery: Removing the strikethrough effect upon the second click!

Currently in the process of learning Jquery and experimenting with using a button to apply a "text-decoration" to a list item upon clicking. However, I encountered an issue where I couldn't figure out how to use the same button to remove the "text-dec ...

How can you align a list next to a set of images using HTML and CSS?

When working with these images in my code, I need to create a list alongside them: <div class="asideContent"> <ul> <li> <p> </p> </li> <li> <p></p> </li> ...

Would you like to place some text within a content box?

I am facing a challenge where I want to insert content into a contentbar that has an opacity of 0.6. However, I do not want the content (such as text or videos) to have the same opacity as the contentbar. I attempted to place them in separate div tags with ...

Can the jQuery live function be triggered without the need for an event?

Using the live function in jQuery requires an event to trigger it. More information can be found in the official API documentation. $(".xyz").live('event', function(){ }); I am trying to make the above function run as soon as the dynamicall ...

It seems that BeautifulSoup and Selenium are unable to locate the div or text elements on the website

I have been attempting to utilize BeautifulSoup or Selenium in order to retrieve the Head to Head text or its corresponding div element on betexplorer (link provided below), but my efforts have unfortunately proved to be unsuccessful. Despite being able to ...

Error message in the browser console: Uncaught TypeError - The function allSections.addEventListener is not recognized

Whenever I inspect my browser console, I keep encountering this error: Uncaught TypeError: allSections.addEventListener is not a function at PageTransitions (app.js:16:17) at app.js:33:1 I find it strange because my VS Code editor does not display any err ...

The TextField component in MUIv5 is showing some frustrating white space in the corners

I've integrated the MaterialUI_v5 library and included a TextField component within a Paper component. The background of the Paper component has been customized to appear in a shade of green. For the Textfield component, I have applied a styling tha ...

What is the reason for all the buttons activating the same component instead of triggering separate components for each button?

I am facing an issue with my parent component that has 3 buttons and 3 children components. Each button is supposed to open a specific child component, but currently all the buttons are opening the same child component when clicked. The children components ...

Whenever I select a link on a navigation bar, it transports me to the desired section of the page. However, I often find that the navbar ends up

Recently, I came across some website templates where clicking on a link in the navbar smoothly scrolls to the corresponding section with perfect alignment. The content at the top of the page aligns perfectly with the top of each division. Upon attempting ...