Home > Back-end >  how to external JavaScript in HTML and CSS
how to external JavaScript in HTML and CSS

Time:03-16

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>

CodePudding user response:

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>

CodePudding user response:

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"));
})
  • Related