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 can’t 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 anundefined
error.To correct this problem, you need to either replace all instances of
$
withjQuery
, or wrap the entire set of functions with a wrapper. For example:Read more in the Codex.
Try following code