Wordpress - Add Javascript to WordPress Menu

Good that it works. If it's for a client or if you just want a cleaner code, you can do it as @Tom J Nowell suggested.

Add a custom menu item, link it to nowhere or anywhere. Find out the menu item ID (every item has one), and then target that ID with jQuery.

$("#menu-item-num").on("click", function(e){ 
      e.preventDefault();
      // olark code here
});

This way, every time a user clicks on that menu-item the script above will be triggered. You can enqueue the jquery script via functions.php.

Update:

  1. Make sure your olark.js is loading. If you're adding it to the footer or header, inspect your page and make sure the script is there. Also, make sure you're not getting any errors in the browser's console.

  2. Wrap your js with a document ready, so that the script executes at the right time:

    jQuery(document).ready(function($) {
      $("#menu-item-38872").on("click", function(e){
      e.preventDefault();
      olark('api.box.expand');
      });
    });
    

The fact that the link is not loading means there's something wrong with the script itself or the script is not loading at all.


Solution #1 (not ideal, but it works):

// Live Chat Utility Link
add_filter( 'wp_nav_menu_items', 'live_chat_utility_link', 10, 2 );
function live_chat_utility_link ( $items, $args ) {
    if ( $args->theme_location == 'utility' ) {
        $items .= '<li><a href="javascript:void(0);" onclick="olark(\'api.box.expand\')" class="livechat">Live Chat</a></li>';
    }
    return $items;
}

Solution #2 (ideal):

With the help of the comments above, here is the solution that worked for me. I created a new file called olark.js and put this code in it:

jQuery(document).ready(function($) {
    $("#menu-item-38872").on("click", function(e){ 
          e.preventDefault();
          // olark code here
          olark('api.box.expand');
    });
});

Then, I enqueued the script in my functions.php with the following code:

function olark_script() {
    wp_register_script( 'olark', get_stylesheet_directory_uri() . '/js/olark.js', array(), '1.0.0', true );
    wp_enqueue_script( 'olark' );
}

add_action( 'wp_enqueue_scripts', 'olark_script' );

If it doesn't work, make sure you are enqueuing your script properly. I am using a child theme, so I had to use get_stylesheet_directory_uri() instead of get_template_directory_uri().