ReferenceError: $ is not defined in JQuery

Total
0
Shares

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

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like

Adding space and tabs in html

Table of Contents Hide Using &nbsp; Using &ensp;Using &emsp;Using &thinsp;Using text-indent CSS propertyLive Demo Html strips more than 1 blank space. So, for example, if you want to write –…
View Post
bootstrap tour links to other pages

Bootstrap tour links to other pages

Table of Contents Hide IntroductionProblem with links to other pagesIntegrationCode ExampleFile 1: Index.htmlFile 2: second.htmlFile 3: /home/third/index.htmlFile 4: tour.jsLive DemoConclusion In this article we will see how Bootstrap Tour links…
View Post