javascriptjquerywordpressroots-sage

Wordpress Roots/Sage template Uncaught TypeError: $ is not a function


so i recently started exploring wordpress, heard about this theme Roots/sage that is similar to how php frameworks work like larvel which im more familiar with.

So in the app.blade.php file just before body tag ends i added this code to check if javascript actually works:

    <script type='text/javascript'>
      $(document).ready(function() {
        console.log( "ready!" );
      });
    </script>

  </body>
</html>

As a result im getting this error: Uncaught TypeError: $ is not a function Okay, so i decided to remove $(document).ready().... literally left only

        <script type='text/javascript'>
            console.log( "ready!" );
        </script>
    
      </body>
    </html>

And it works perfectly!

Including the file with sages assets/scripts/main.js file shouldn't matter if jquery/javascript is already included i should be able to throw a random js function at the bottom of each page, no?

So my question is, can someone explain why is it throwing the error and how to fix it, i would like my page to be fully loaded "ready" before outputting any scripts. I hope this makes sense..


Solution

  • You can wrap it inside a function like this to make it work:

    ( function( $ ) {
        console.log( "ready!" );
    }( jQuery ) );
    

    Another way would be to replace the $ width the word jQuery:

    jQuery(document).ready(function() {
            console.log( "ready!" );
    });
    

    Both solutions should work fine in wordpress.