0

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>

1 Answer 1

1
  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.

Sign up to request clarification or add additional context in comments.

3 Comments

In which file should I load jQuery? The JavaScript(website.js) or the EJS(website.ejs) file?
@AnonUser In the EJS/HTML like you already are. You just need to change the order. You can't put a <script> tag inside of JS code (well, at least not in that format).
Worked perfectly! Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.