Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 786
byronjt Avatar asked Dec 11 '22 16:12

byronjt


2 Answers

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

like image 121
Kylar Avatar answered Dec 22 '22 05:12

Kylar


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.

like image 30
Steven McElveen Avatar answered Dec 22 '22 04:12

Steven McElveen