Harsh Vardhan
Harsh Vardhan

Reputation: 41

External javascript file not working in HTML file

I'm trying to change the property of a div from a javascript file but it's not working, it's working if I put it inside body but I want to work it from external js file for some project.

HTML file

<!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 trying to change the property of a div from a javascript file but it's not working, it's working if I put it inside body but I want to work it from external js file for some project.

Upvotes: 1

Views: 1247

Answers (2)

Eduardo Jim&#233;nez
Eduardo Jim&#233;nez

Reputation: 378

When you import your JS file at <header> your JS loads and then your body.

When you import your JS file after <body> your body loads and then your JS.

The first solution is to put your JS file after </body>. The second one is to put the function call inside the window onload event listener

Upvotes: 2

rigojr
rigojr

Reputation: 361

you have to put the <script src="javascript/cal.js"></script> at the end of the </body> tag.

You cannot get element from the DOM before the browser get it through the HTML.

Upvotes: 0

Related Questions