HTML JavaScript Collapsible not collapsing when .html, .js and .css are in separate files

62 views Asked by At

This is an example from W3, "How TO - Collapse". It should be simple, but I'm at a loss to get it working in separate files.

When the JavaScript and CSS code are in the index.html, the collapsible works.

But when the .html, .CSS and .JS are separate files in the same folder on my PC, it does not collapse. The CSS works because the 'hover' changes the button color. But not the JavaScript.

The file names I'm using are index.html, javascript.js and styles.css.

It's pretty much copied from W3. This is being used for an HTML Help file for a Windows application, so it will not be on the Web. What am I missing??

HTML: 

<!DOCTYPE html>
<html>
<head>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="./styles.css"></link>
<script type="text/javascript" src="./javascript.js"></script>

</head>

<body>

<h2>Collapsibles</h2>

<p>A Collapsible:</p>
<button type="button" class="collapsible">Open Collapsible</button>
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor  
</div>
</body>
</html>

JAVASCRIPT:

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
   this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
    } else {
      content.style.display = "block";
    }
    }
);
}

CSS: 


/* Style the button that is used to open and close the collapsible content */
.collapsible {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

/* Add a background color to the button if it is clicked .mouse over it (hover) */

.active, .collapsible:hover {
  background-color: #ccc;
}

 /* Style the collapsible content. Note: hidden by default */

.content {
  padding: 0 18px;
  display: none;
  overflow: hidden;
  background-color: #f1f1f1;

}`
1

There are 1 answers

4
Bob Sander-Cederlof On

The javascript is being read and executed before the rest of the page is loaded.

The simplest fix is to move the line <script>...</script> out of the <head> into the end of the <body>, right before the </body> line.

Tested and it works. However, you can leave the script line where it is if you add "defer" to it.