Asl.har
Asl.har

Reputation: 55

jQuery doesnt work in an external javascript file

So I'm a beginner in JavaScript.

I have this simple HTML file where I tried to test jQuery with $("h1").hide() and my problem is that the jQuery code works in the HTML but when I try to put this code in an external JavaScript file testjs.js and insert it via script tag to the head, it doesn't works anymore. Just to be clear, the external JavaScript file is recognized, for example when I put document.write("third test") in the external JS file it will show "third test". Hope I've been clear

<!doctype html>
<html>
    <head>
        <title>Test</title>
         <meta charset="utf-8"/>
         <script src="jquery-3.3.1.min.js"></script>
         <script src="js/testjs.js"></script>
   </head>
   <body>
       <h1>first test</h1>
       <p>second test</p>

   <!-- this works only here but not in external js file
   <script>
    $("h1").hide();
   </script>
   -->
   </body>
</html>

Upvotes: 0

Views: 80

Answers (2)

Ele
Ele

Reputation: 33736

The problem is regarding to document loading execution. The execution of $('h1').hide() is happening just before the document is fully loaded.

Three alternatives

  • Put the script at the bottom of the body.

    <script src="js/testjs.js"></script>
</body>
  • Bind the event DOMContentLoaded and put the logic of hiding within it.

document.addEventListener("DOMContentLoaded", function(event) {
   $('h1').hide();
});
  • Use the built-in function ready from jQuery

$(document).ready(function() {
    $('h1').hide();
});

Upvotes: 2

Ian Foulk
Ian Foulk

Reputation: 51

It could be that the DOM has not loaded the h1 element you are trying to hide. Try using this code in testjs.js.

$(document).ready(function() {
    $('h1').hide();
});

When manipulating elements you should wait for the document to fully load.

Upvotes: 4

Related Questions