Basically $ is an alias of jQuery() so when you try to call/access it before declaring the function, it will endup throwing this $ is not defined error . This usually indicates that jQuery is not loaded and JavaScript does not recognize the $. Even with $(document).ready , $ is still going to be undefined because jquery hasn't loaded yet.
To solve this error:
Load the jQuery library at the beginning of all your javascript files/scripts which uses $ or jQuery, so that $ can be identified in scripts .
There can be multiple other reasons for this issue:
Path to jQuery library you included is not correct
The jQuery library file is corrupted
Working offline
Conflict with Other Libraries