JavaScript error: $ is undefined

Capture

This error comes when the jQuery library was not referenced or not loaded at all or not loaded properly.

Solution:

  1. Add script reference to the jQuery library in your html file: you can download it and add it into your project or reference it from CDN.
    <head>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="MyJavaScript.js"></script>
    </head>
    
  2. The order of your referenced scripts is important: make sure to add the jQuery library before your scripts.
    So if we have a JavaScript file called MyJavaScript.js with the following code in it:

    $(document).ready(function () {
    $("myButton").click(function (event) {
    alert("Hello world!");
    });
    });
    

    This will not work:

    <head>
    <script src="MyJavaScript.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    </head>
    

    This will work:

    <head>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="MyJavaScript.js"></script>
    </head>