How can I add onclick events to WordPress Menus

I’m trying to add an onclick event to a WordPress menu that uses a nav walker. While I understand code and php I’m not very experienced with the WordPress system nor would I could myself an experienced coder.

I have a menu item that I’d like to add an onclick event to it but I can’t figure how to do this.

Read More

Normally I’d use code such as the following

<a href="tel:1300XXXXXX" onclick="__gaTracker('send','event','phone call','click');"></a>

The menu itself looks like this

<nav>
    <ul class="sf-menu">
        <li id="menu-item-2785" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-2785"><a href="tel:1300XXXXXX"><span class='icon-phone'></span>Call us today 1300 XXX XXX</a></li>
    </ul>
</nav>

While I can specific the link in the menu to be a tel: link there is no way from what I see to add an onclick to menu item itself.

I tried a plugin called the Jin Menus but for the life of me I couldn’t it to work.

I also found these articles but haven’t been smart enough to get them to work at this point

How to add an onclick function to wordpress menu item (For google cross domain tracking)

I would greatly appreciate any help you could provide.

Related posts

Leave a Reply

3 comments

  1. if you want it for all of the menu items, use a class to identify it or if it’s different for each item use an id.

    in your js file:

    $( ".menu-item" ).click(function() {
      // your on click code here
    });
    

    change the .menu-item to whatever class/id you wish to target

  2. On a one page site, for example, you’ll want to track the click Events for each menu item as your navigation, so I like adding a function tracking the Anchor tag.

    $('a').click(function(){
        ga('send', 'event', 'Navigation', 'Click', $(this).text());
    });
    

    For me, the more data on clicks the better, but you could do some conditional weeding if necessary.

  3. This is what I used in the end. Thanks everyone for your help.

    <script>
         (function($){
             $( ".sf-menu" ).click(function() {
                 __gaTracker('send','event','phone call','header');
             });
         })(jQuery);
    </script>`