JavaScript file from an external source not functioning within an HTML document

I'm facing an issue trying to modify a div's property from a JavaScript file. It works when placed inside the body, but I need it to function from an external JS file for a specific project.

Here is the structure of my files:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Calendar</title>
    <link rel="stylesheet" href="css/styles.css">
    <script src="javascript/cal.js"></script>
  </head>
  <body>

    <div id="container">

      <div id="calendar-view">

      </div>

      <div id="events-view">

      </div>

    </div>


  </body>
</html>

CSS File:

*{
  box-sizing: border-box;
}

#calendar-view{
  float: left;
  width: 70%;
  background-color: blue;
  height: 200px;
}

#events-view{
  float: left;
  width: 30%;
  height: 200px;
  background-color: red;
}

#container::after{
  content: "";
  clear: both;
  display: table;
}

JavaScript File:

function startUp(){
  document.getElementById("calendar-view").style.display = "none";
}

startUp();

I'm encountering difficulty in altering a div's property through an external JavaScript file rather than within the body itself for a specific project.

Answer №1

When you include your JavaScript file in the <header> section, the JS code loads first followed by the body content.

If you place your JavaScript file after the <body>, then the body content will load first before the JS code.

To address this, one option is to position your JS file after the closing </body> tag. Another approach is to insert the function call within the window onload event listener

Answer №2

Make sure to place the

<script src="javascript/cal.js"></script>
at the bottom of the </body> tag.

Attempting to access an element from the DOM before it has been loaded by the browser is not possible.

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

What is the best method to eliminate a "0" entry from a javascript event array?

Hello, I've got an array structured as follows: let test = ["testOne:,O,U,0","testTwo:R,C,0","testTree:1.334","testFour:r,z"]; I'm looking to iterate through the array and remove any occurrences of the cha ...

Creating an Angular service that checks if data is available in local storage before calling an API method can be achieved by implementing a

I am currently working on developing an Angular service that can seamlessly switch between making actual API calls and utilizing local storage within a single method invocation. component.ts this.userService.getAllUsers().subscribe(data => { conso ...

Obtain specific text from elements on a website

How can I extract a text-only content from a td tag like 'Zubr Polish Lager 6%'? <td width="35%">Amber Storm Scotch Ale 6% <br/>SIZE/LIFE: 330ml <b>CASE</b> <br/>UOS ...

Using Three.js to display a PerspectiveCamera with a visible bounding Sphere

My challenge is to create a Scene that loads a single .obj file where the object is fully visible in the PerspectiveCamera upon scene initialization. The field of view (FOV) is set at 60 The objects vary in size TrackballControls are utilized for camera ...

Using ThreeJS in conjunction with NextJS requires that class constructors be called with the 'new' keyword

Seeking assistance with rendering a basic scene within a nextJS route named "lab2". Encountering the following error: Error: class constructors must be invoked with 'new' Call Stack: renderWithHooks mountIndeterminateComponent ...

Determine if the data in an HTML table should be spanned when it

I'm facing a scenario where my HTML table contains duplicate data in a particular column, as illustrated below I am looking to automatically merge the cells of rows in the HTML table if the data in them is identical, similar to the table displayed be ...

What is the best way to combine elements from different arrays to create a comprehensive listing?

My current function successfully pulls data from another source to create a listing. However, the data I require is spread across multiple arrays, causing some items to be returned as "undefined." At the moment, I am only fetching data from the products a ...

Getting rid of a texture in three.js

I am attempting to deallocate a texture once it has been loaded in three.js. The texture is loaded using var tex = THREE.ImageUtils.loadTexture("image.png"); and it is being displayed correctly. However, when I attempt to use: tex.dispose(); I consist ...

The Bootstrap tabs are not correctly displaying the content

Hey there, I'm currently working on a project that involves using bootstrap tabs (BS4) within a form. One of the requirements is to have forward and back buttons for form navigation, and I'd like to leverage BS4's tab('show') fun ...

"Exploring the Art of Showcasing Duplicate Image Count from User Input in an

I need to showcase multiple duplicates of 2 different images on a webpage. Users are asked for the duplication speed, which I have already implemented, and also how many copies of each image they want. function show_image() { var img = document.create ...

I am trying to figure out how to properly utilize server-only functions within Next.js middleware

In my current project, I am utilizing Next.js 13 along with the App Router feature. While attempting to include a server-specific fetch function in middleware.js, an error message is encountered: Error: Unable to import this module from a Client Compone ...

Tips for extracting and utilizing a JSON object provided by the parent page:

Sorry in advance if this question has already been addressed. I've spent hours searching on Google, but haven't found a satisfactory answer yet. Below is the code snippet I'm working with: <ion-content> <div class="list"> ...

Problems with Arrays in Google Apps Script

I'm currently developing an apps script that loads XML data into a function and parses it based on user input. The XML structure is fairly simple: <?xml version="1.0" encoding="UTF-8"?> <Records> <Record> <username&g ...

Alignment issues with images

I am trying to put together a collection of images that function as links and light up when hovered over. However, my attempt to add a <div class="hover"> in front of each image caused them to no longer display in a horizontal line. How can I resolve ...

"Unable to get 'vertical-align middle' to function properly in a table

Can someone please review my code at http://jsfiddle.net/4Ly4B/? The vertical alignment using 'vertical-align: middle' on a 'table-cell' is not centering as expected. ...

Sending multiple objects using Ajax and fetching them in PHP

I'm facing an issue with posting a form and an array to my PHP script. My current approach involves using the following code: var json_data = JSON.stringify(data_vendor); //array to be posted $.ajax({ url: &ap ...

How can I selectively disable all buttons except for one and then re-enable them all with a single click using jQuery?

I'm working on creating a basic toggle switch using jQuery, but I've run into an issue where it's disabling all buttons when clicked, including the toggle button itself. $(".toggleButton").click(function() { $('button').not(this ...

Flashing Dropdown Navigation Bar on Internet Explorer and Firefox

Hey there! I have been working with a drop-down menu on various websites without any issues, but for some reason, it's acting up in this specific application (). The menu seems to flicker and is not properly positioned in Firefox and IE8-10, although ...

Encountered an error: Uncaught TypeError - Unable to access property 'active' as it is undefined within React code

<script type="text/babel"> class Frame extends React.Component{ render(){ return ( <div> <h2 className="os-animation" dat ...

Attach a Material-UI Popper component to a customized edge label in a React Flow

After finding inspiration from this particular example in the react-flow documentation, I decided to create my own customized version. It showcases a Material Ui Popper that appears when the edge is selected. However, my problem arises when attempting to z ...