0

here is a code of HTML including JS and I want the JS to be an external file but it wont work , how to solve it and make the element move while clicking when it external

<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}
</script>
  • Please visit the [help], take the [tour] to see what and [ask]. If you get stuck, post a minimal reproducible example of your attempt, noting input and expected output using the [\[<>\]](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Mar 15 '22 at 15:01

2 Answers2

1

if you want to use external JS file inside your html file then you have to put the script tag inside the head of the html file

<head>
  <script src="file.js" defer></script>
</head>
Alucard
  • 58
  • 5
-1

You need to put the script tags after the elements (before the </body>) or wrap in a load handler:

window.addEventListener("DOMContentLoaded", function() { 
  var acc = document.getElementsByClassName("accordion"); 
  .....
})

Also you likely want to delegate from the accordion container instead of looping

document.getElementById("accordionContainer").addEventListener("click", function(e) { 
  const tgt = e.target.closest(".accordion"); 
  if (tgt) tgt.classList.toggle("active"); 
  tgt.nextElementSibling.classList.toggle("hide", !tgt.classList.contains("active"));
})
mplungjan
  • 169,008
  • 28
  • 173
  • 236