Adding JS to wordpress menu item
-
Trying to customize a wordpress menu list item. The menu was created through the wordpress admin panel. I am unable attach the javascript function show/hide to a specific wordpress menu list item.
I have added a class to the menu list item through the wordpress admin area > screen options > CSS Classes. However this class is not triggering the javascript function show/hide.
What am I missing to in order to attach the javascript function to the wordpress generated navigation menu?
$(document).ready(function(){
$(“.hide”).click(function(){
$(“.webform”).hide(500);
});
$(“.show”).click(function(){
$(“.webform”).show(500);
});
});
-
First of all, your js should look more like this:
jQuery(document).ready(function($) { $(".hide_nav").click(function(){ $(".webform").hide(500); }); $(".show_nav").click(function(){ $(".webform").show(500); }); });Try using more specific classname,so as not to cause conflict issues with other css classes. Also if you are trying to hide the entire list. I suggest using the
wp_nav_menu()to add your class to the ul element of the menu list once.Thanks for responding. I have a menu list with a link to the contact form. The behavior I am trying to achieve is to show the contact form when the link is clicked. The contact form is hidden by default.
Adding a class through the admin area panel options to the menu link works, I can add css rules to the menu item.
However, the menu item class does not see the javascript function.
Ok now I get what you are trying to do. How are you then loading your script on the page/pages that has the menu link?..
The javascript is placed at the bottom of the footer.php file.
Now that you mention it. I think this is the problem. The javascipt doesn’t automatically load by placing it in the footer.php file. I am not sure how to load it properly.Use the
wp_enqueue_script()function to properly load your scripts.
https://codex.ww.wp.xz.cn/Function_Reference/wp_enqueue_scriptI will give it a try!
Thanks very much for your help!
The topic ‘Adding JS to wordpress menu item’ is closed to new replies.