Add JavaScript event onClick to Wordpress Menu Item

Hi

I’d like to add a JavaScript event onClick to a Wordpress Menu Item.
This Wordpress Menu is associated to a Navigation Collapsed element into my main Header.

I’d like that this specific Menu Item generate two events onClick:

  1. “zE(‘webWidget’, ‘open’)”
  2. Close Navigation Collapsed element

Thank You

Daniele

Hi Daniele,

Thanks for reaching out.

That’s doable, but I can only provide the idea how it can be achieved as we don’t provide customization in the forum. The code you’ll need is in this format

jQuery ( function($) {

$(document).on('click', '#menu-item-2234 > a ', function(e) {

e.preventDefault();

//your code here

$(this).parentsUntil('.x-off-canvas-content').parent().prev().trigger('click'); //this closes the off canvas

} );

} );

The idea is, changing #menu-item-2234 with the ID of your menu items, example

You can use the browser developer tools to inspect your site’s code and your preferred ID. This might help https://kb.oboxthemes.com/articles/how-to-get-css-styles-for-elements/

Once done, you can simply change the line //your code here with your own code, like zE('webWidget', 'open'). The code I provided works and tested, but it comes down to the code that you’ll add in which we can’t further cover.

Thanks!

Dear Rad

Thank you for your precious support.

It works fine on Desktop.
It doesn’t works on Mobile.

Any suggestion?

Thank You

Daniele

Hi Daniele,

Try updating this part .on('click' to .on('touchstart click'

more details about touchstart Event.

Hope it helps,
Cheers!

Hi @friech

I updated as suggested, but nothing happens.

The ID #menu-item-2236 seems to disappear in the mobile version.

Thank You

Daniele

Hi Daniele,

Another approach would be editing your menu item in the dashboard and entering something into the “CSS Classes (optional)” field. Let’s say you put custom-target in there for example. Now your jQuery selector can be:

'.custom-target > a'

That will cause the event handler to work on all instances of that menu item.

Now it works fine!

Thank You very much

Daniele

We are delighted to assist you with this.

Cheers!

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.