jQuery on Underscores menu

I’m trying to add a class to an element within the main menu, but nothing is happening. I’m using Underscores starter theme, which has this in the header.php:

<?php
    wp_nav_menu( array(
        'theme_location' => 'menu-1',
        'menu_id'        => 'primary-menu',
        'after'          => '<span class="fa fa-times"></span>',
    ) );
?>

I then put this in the navigation.js file (also tried inline in the footer.php):

$(".menu-item-has-children .span").click(function() {
    $(".menu-item-has-children .sub-menu").removeClass("toggled");
    $(this).next(".sub-menu").toggleClass("toggled");
});

But nothing happens. I’ve also tried a simple:

$('body').click(function() {
    alert("Yeah!");
});

And nothing happens there either. This does work:

window.onload = function() {
    alert("Yeah!");
}

jQuery is loading:

<script type="text/javascript" src="http://example.com/wp-includes/js/jquery/jquery.js?ver=1.12.4"></script>

navigation.js is enqueued in functions.php:

function themename_scripts() {

wp_enqueue_style( 'themename-style', get_stylesheet_uri() );

wp_enqueue_script( 'themename-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true );

wp_enqueue_script( 'themename-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true );

if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
    wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'themename_scripts' );

…So what basic error have I made?

1 Answer
1

You haven’t passed jquery as a dependency for your script, and you are using the dollar sign too, which is not directly supported in WordPress due to conflict.

First, pass jQuery as a requirement while enqueuing your navigation.js:

wp_enqueue_script( 
    'themename-navigation', 
    get_template_directory_uri() . '/js/navigation.js', 
    array('jquery'), 
    '20151215', 
    true 
);

Then, wrap your code in a self invoking function:

(function($){
    // You have access to $ here
})(jQuery);

Or even better, define the $:

var $ = jQuery.noConflict();

$('body').click(function() {
    alert("Yeah!");
});

Done.

Leave a Comment