Search code examples
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.

  • Installed the theme with success,
  • Set it up, all is working,
  • Browsersync- working,
  • Created few custom pages -all is working perfectly, Now it's time to add some javascript to the app.blade.php file in layouts folder. If i understand correctly jquery and javascript is already included through sage setup, because bootstrap works perfectly.

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.