Callum Smith
Callum Smith

Reputation: 75

jQuery code works in console but not in site

I have the following jQuery code in a wordpress site.

jQuery(document).ready(function() {
   jQuery(".responsive-menu > .menu-item").click(function(event){
   if (event.target !== this)
   return;
   jQuery(this).find(".sub-menu:first").slideToggle(function() {
   jQuery(this).parent().toggleClass("show");
  });
 });
});

The class being toggled sets the ".sub-menu" element to be displayed from "none" to "block".

It works fine in the console in chrome dev tools, but not in the page, and it is placed after the DOM element is created.

If i change the code to the following, A alert executes, so the jQuery code executes no problem.

 jQuery(document).ready(function() {
  alert("working");
 });

Any suggestions as to why this is?

EDIT:

The solution was

jQuery(".menu-item").click(function(event){

instead of

jQuery(".responsive-menu > .menu-item").click(function(event){

Thanks for the help guys

Upvotes: 1

Views: 145

Answers (1)

Suraj Kc
Suraj Kc

Reputation: 97

try this instead.

(function($){
   $(document).ready(function() {
       $(".responsive-menu > .menu-item").on('click',function(event){
           if (event.target !== this)
               return;
           $(this).find(".sub-menu:first").slideToggle(function() {
               $(this).parent().toggleClass("show");
           });
        });
    });
})(jQuery)

Upvotes: 1

Related Questions