javascriptjqueryjquery-waypoints

JS no longer working after WordPress update - Uncaught TypeError: $ is not a function


I updated a website I am working on to the latest WordPress last week. None of the custom JS is working anymore and I can't work out why.

Even if I remove it in sections to try and isolate the issue, I always get 'Uncaught TypeError: $ is not a function'.

I cannot work out what has caused this to happen.

As far as I can see, all the scripts load as expected.

Unfortunately all the JS in my custom file has been acquired either from Stack Overflow or other online resources - I did not write it myself (only amended) and thus am struggling to diagnose the issue.

Any help would be appreciated

// apply effect to pages

var $headereffect = $('.hero-effect');

$headereffect.waypoint(function (direction) {
   if (direction == 'down') {
   $headereffect.addClass('hero-effect-animation');
   } else {
   $headereffect.removeClass('hero-effect-animation');
   }

}, { offset:'1px' });



// apply effect to default page headers



var $headereffect = $('#page-header');

$headereffect.waypoint(function (direction) {
   if (direction == 'down') {
   $headereffect.addClass('hero-effect');
   } else {
   $headereffect.removeClass('hero-effect');
   }

}, { offset:'1px' });

Solution

  • My wild guess is to use jQuery instead of the $ as sometimes the latter is used by other scripting libraries and this causes issues and conflicts.

    So

    var $headereffect = $('.hero-effect');
    

    becomes

    var $headereffect = jQuery('.hero-effect');
    

    This will fix the current issue but others also may be raised on a later stage. Inspect your code and make sure you use a consistent jQuery reference.

    Options to handle the $ issue the jQuery way can be found here. From a practical point of view, you can put jQuery into "no conflict" mode by using shortcut for jQuery. In this case "$j" instead of the default "$":

    var $j = jQuery.noConflict();
    $j(function(){
        $j("#sidebar li a").hover(function(){
            $j(this).stop().animate({
                paddingLeft: "20px&"
            }, 400);
        }, function() {
            $j(this).stop().animate({
                paddingLeft: 0
            }, 400);
        });
    });
    

    A best practice as Wordpress suggest is to wrap your code in immediately invoked function expression, pass jQuery to it and use the $ internally like this:

    ( function( $ ) {
        // Your code goes here
    } )( jQuery );