AnonUser AnonUser - 5 months ago 34
jQuery Question

EJS File Not Recognizing JavaScript File's Code

I am creating a website, I am using a NodeJS server. In my public folder I have a script named website.js and it has the jQuery code to give a console.log when the h1 is clicked. (Code Below). But when I click on the h1 in the browser it does not work. The file is loaded properly, gives no 404 error and my CSS stylesheet works fine.

Further Testing: I did a simple test to see if it would give back the text when I called the variable (test code below) it responds with: "" (two quotation marks) so it must not be recognizing it.

//Test code
var xyz = $("#testh1").text();
//jQuery Code
$("#testh1").on("click", function(){
console.log("Clicked");
});


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/javascripts/website.js"></script>
<link rel="stylesheet" type="text/css" href="/stylesheets/website.css">
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<title>test</title>
</head>
<body>

<h1 id="testh1">TEST</h1>

</body>
</html>

Answer
  1. You need to load jQuery before your script.

    <script src="https://path-to-jquery"></script>
    <script src="/javascripts/website.js"></script>
    
  2. You need to wait for the DOM to be ready before accessing any elements in it. You can either do it with the following code:

    $(document).ready(function() {
        $("#testh1").on("click", function(){
             console.log("Clicked");
        });
    });
    

or by putting your <script>s at the bottom of the <body> instead of in the <head>.

    <script src="https://path-to-jquery"></script>
    <script src="/javascripts/website.js"></script>
</body>

You're getting an empty string in your test code because your #testh1 element hasn't been loaded yet.

Comments