How to repair & ldquo; Undefined is not a & rdquo; In wordpress

advertisements

I am converting a megamenu from html/css/javascript to work in wordpress. I have created a working walker and all is set. The problem is, i cant get the javascript to work. The javascript is supposed to trigger the top level li to open a mega menu section when clicked and also close it when clicked again.

I have used this javascript file:

var swMegaMenu = (function() {

    var $listItems = $( '#sw-hrmenu > ul > li' ),
        $menuItems = $listItems.children( 'a' ),
        $body = $( 'body' ),
        current = -1;

    function init() {
        $menuItems.on( 'click', open );
        $listItems.on( 'click', function( event ) { event.stopPropagation(); } );
    }

    function open( event ) {

        if( current !== -1 ) {
            $listItems.eq( current ).removeClass( 'sw-hropen' );
        }

        var $item = $( event.currentTarget ).parent( 'li' ),
            idx = $item.index();

        if( current === idx ) {
            $item.removeClass( 'sw-hropen' );
            current = -1;
        }
        else {
            $item.addClass( 'sw-hropen' );
            current = idx;
            $body.off( 'click' ).on( 'click', close );
        }

        return false;

    }

    function close( event ) {
        $listItems.eq( current ).removeClass( 'sw-hropen' );
        current = -1;
    }

    return { init : init };

})();

And i have inserted this into the footer.php:

<script>
            $(function() {
                swMegaMenu.init();
            });
        </script>

The problem is i get this error in the footer.php:

<script>
            $(function() { // Uncaught TypeError: Undefined is not a function
                swMegaMenu.init();
            });

</script>

and this error in the javascript file:

var swMegaMenu = (function() {

    var $listItems = $( '#sw-hrmenu > ul > li' ), // Uncaught TypeError: Undefined is not a function
        $menuItems = $listItems.children( 'a' ),
        $body = $( 'body' ),
        current = -1;

You're using WordPress's default jQuery instance, but you're not using noConflict() wrappers.

In the noConflict() mode, the global $ shortcut for jQuery is not available. This is why you're seeing an undefined error.

To correct this problem, you need to either replace all instances of $ with jQuery, or wrap the entire set of functions with a wrapper. For example:

(function($) {
    // Inside of this function, $() will work as an alias for jQuery()
    // and other libraries also using $ will not be accessible under this shortcut
})(jQuery);

Read more in the Codex.