Add Javascript to WordPress Menu

Is there a way to put javascript in the URL portion of a WordPress menu item? I have a live chat function on my site, and I am supposed to put this code onto the site to make a link to open the live chat (as suggested here).

<!-- BEGIN OLARK CHAT LINK -->
<a href="https://wordpress.stackexchange.com/questions/153018/javascript:void(0);" onclick="olark('api.box.expand')">
    Click here to chat!
</a>
<!-- END OLARK CHAT LINK -->

The client wants the link in the utility nav bar, which was created used a WordPress menu in the WordPress dashboard. But when I copy and paste javascript:void(0);" onclick="olark('api.box.expand') into the URL box in the WordPress dashboard, it just disappears and the link remains inactive.

Something I read said that maybe I could put a custom class on the link in question and then write a Javascript function that fires when the link with that class is clicked. I tried that, though, and I couldn’t get it to work. I don’t know much Javascript, so it’s possible I was writing it entirely wrong.

Does anyone know how to do this? I would like to do it without using a plugin.

4 s
4

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.

Leave a Comment