Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript only works in <script> tags, not js file

I'm making a clickable dropdown menu. But when I run the javascript in its own js file the js doesn't work. However, when I put the javascript in tags in my html document, the menu works perfectly fine. Does anyone know how to make the javascript work in its own js file?

function myFunction() {
 document.getElementById("myDropdown").classList.toggle("show");
}

window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
};
like image 280
COOKIE Avatar asked Oct 22 '25 17:10

COOKIE


2 Answers

Try

document.addEventListener('DOMContentLoaded', function() {
  // do stuff here

}, false);
like image 161
Ronnie Royston Avatar answered Oct 25 '25 07:10

Ronnie Royston


You need to create a JS file called script.js and then add this to HTML document before closing body tag:

<script src="script.js"></script>

I assume you are not including the script correctly. Check your console for errors.

Also, if you are including script in the head section, it could be loaded before the HTML, therefore the selectors possibly could not be found. Including script at the end of the HTML document (before closing body tag) would assure the document is loaded before script is executed.

like image 27
HelpNeeder Avatar answered Oct 25 '25 07:10

HelpNeeder