<script> tag not working in html <head> or external js file

logicmyth picture logicmyth · Feb 20, 2018 · Viewed 12.4k times · Source

Trying to require js in an HTML file. Required the external js files through the tags seen below

<script type="text/javascript" src="scripts/ui.js"></script>
<script type="text/javascript" src="scripts/events.js"></script>

These script tags did not work because the event handlers inside them did not fire. So, in a previous project I had luck writing all the js logic in tags within the of the HTML, which looks like this (also in this project along with external js) Also, the html file has a button with "shuffle" as its class.

<script type="text/javascript">
$(".shuffle").click(function(){
  console.log("hello");
  let arr = onShuffle();
  shuffleSuccess(arr);
});

</script>

The interesting thing about this is I put the above function in the console of the index.html/project's file and the click handler worked as well as the shuffleSuccess function, which is in the external js file. Thanks!

Answer

Jon P picture Jon P · Feb 21, 2018

Your script needs to execute after your button is in the DOM. Your options are to place it at the bottom of the page, just before the closing body tag, or use document.ready as shown below:

//This waits until all objects are loaded in the DOM
$(document).ready(function() {
    //Then assigns the event handler
    $(".shuffle").click(function(){
      console.log("hello");
      let arr = onShuffle();
      shuffleSuccess(arr);
    });
});

If your script is in an external file $(document).ready is a good option.

Alternatively, you could use http://api.jquery.com/on/ . This will apply the click handler to anything with the class shuffle that is in the body, even if it is added later. This is arguably better than $(document).ready

$("body").on("click", ".shuffle", function() {
  console.log("hello");
  /*let arr = onShuffle();
  shuffleSuccess(arr);*/
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="shuffle">Shuffle</button>

If you want to change your script order, something like the following will work:

<html>
   <head>
      <title>Your Page</title>
      <!-- Some CSS Links -->
   </head>
   <body>
     <!-- Some Content --> 
     <input type="button" value="I'm a button">
     <!-- Some more content -->
     <!-- Note: the script comes after the button is placed -->
     <script type="text/javascript">
     $(".shuffle").click(function(){
        console.log("hello");
        let arr = onShuffle();
        shuffleSuccess(arr);
     });
     </script>
  </body>
</html>