When I was creating my first jquery project in 2012, I got a weird referenceerror: $ is not defined. I was very excited with JQuery but this error broke my heart. I was tearing my hair because I was doing everything right and still getting the error. This is a common mistake done by beginners. In this article we will look at the ways to resolve it.

Why this error appears?

There are few reasons for $ not defined error –

  1. If you are using jquery functions like $('#selector') before loading jquery script on webpage.
  2. If multiple libraries have defined $ then browser gets confused and shows error. Make sure that whatever libraries you are using, they should not have defined $ as keyword except jQuery.

Code Example

The below code snippet will raise β€œ$ is not defined” error because we are loading jquery after using $ function.

<!DOCTYPE HTML>
<html>
  <head></head>
  <body>
    <p>jQuery will raise error</p>
    <script>
      $('p').html('jQuery runs fine here');
    </script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </body>
</html>

To resolve the error and correct this code, we need to shift our js after jquery script. So, the below code will run fine.

<!DOCTYPE HTML>
<html>
  <head></head>
  <body>
    <p>jQuery will raise error</p>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
      $('p').html('jQuery runs fine here');
    </script>
  </body>
</html>

Live Demo

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles