I have linked a jquery file but I can't use it

Viewed 70

I have linked my HTML to jquery but when I run it in Microsoft edge, it outputs

"Help.js:1 Uncaught ReferenceError: $ is not defined at Help.js:1 (anonymous) @ Help.js:

Code:

$(document).ready(function(){
    $(".navBar").hover(function(){
        $(this).css("border","2px solid black")
    })
})
navBar{
    display: flex;
    position: sticky;
    top:0;
    padding: 20px;
    border: none;
    width: 100%;
    justify-content: center;
    background-color: gainsboro;
    z-index: 2;
    
 }
 #Title{
     color: black;
     font-family: monospace;
 }
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>A Random Website</title>
</head>
<body>
    <script src="style.js"></script>
    <script src="https://code.jquery.com/jquery-latest.js"></script>
    <div class="navBar">
        <div>
            <h1 id="Title">SomeRandomWebsite</h1>
        </div>
    </div>
</body>
</html>

2 Answers

It is because you're using $ before jQuery has loaded.


// Instead of:
//...
    <script src="style.js"></script>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
//...
// Use this:
// ...
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script src="style.js"></script>
// ...

And move those script tags to the line before the closing </body> tag. i.e:

// ...
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script src="style.js"></script>
    </body>
</html>

Add scripts in your head tag and first load jquery and then your custom style.js file.

Also, add the defer attribute to your script.

Defer attribute when present, specifies that the script is executed when the page has finished parsing. You can read more about defer

$(document).ready(function() {
  $(".navBar").hover(function() {
    $(this).css("border", "2px solid black")
  })
})
.navBar {
  display: flex;
  position: sticky;
  top: 0;
  padding: 20px;
  border: none;
  width: 100%;
  justify-content: center;
  background-color: gainsboro;
  z-index: 2;
}

#Title {
  color: black;
  font-family: monospace;
}
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>A Random Website</title>
  <script src="https://code.jquery.com/jquery-latest.js" defer></script>
  <script src="style.js" defer></script>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="navBar">
    <div>
      <h1 id="Title">SomeRandomWebsite</h1>
    </div>
  </div>
</body>

</html>

Related