3

I was basically implementing this from W3School: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_accordion_symbol

I tried making the javascript into a separate file called accordion.js

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    } 
  }
}

and tried calling the javascript file via HTML doing this:

<script type="text/javascript" src="accordion.js"></script>

Can anyone tell me what I can do to fix this and help explain why it didn't work?

TBA
  • 63
  • 2
  • 9

2 Answers2

2

Just to add a little more to the answer given in the comments :

Here is a long answer on the subject : Load and execution sequence of a web page?.

But, if we simplify, the parsing of the HTML is synchronous. The browser needs to parse the HTML before he can access the DOM via javascript, in your case:
var acc=document.getElementsByClassName("accordion");

That is why, and to prevent bugs like you had, that $(document).ready() from jQuery is very famous https://learn.jquery.com/using-jquery-core/document-ready/

Community
  • 1
  • 1
Kevin Amiranoff
  • 13,440
  • 11
  • 59
  • 90
1

Depending on what errors you might be getting it sounds like it's likely the JS file isn't in the same directory.

mysticalstick
  • 2,479
  • 5
  • 16
  • 21