JSFiddle Code working, but not working when in wordpress?

My JSFiddle Code works perfectly within the workspace. Just trying to do a simply show/hide of a menu that has children:

$('#menu-product-categories .sub-menu').hide(); //Hide children by default

$('#menu-product-categories li a').click(function(event){
    if ($(this).next('ul.sub-menu').children().length !== 0) {     
        event.preventDefault();
    }
$(this).siblings('.sub-menu').slideToggle('slow');
});

However, when I take that same exact code and put it into my wordpress site, it does not function. I’m adding the jquery to the header of the site exactly how it is done within the JSFiddle, and I directly copy/pasted the menu structure from my wordpress site. I don’t see how this can happen? Any advice would be helpful

Read More

Thanks for your time.

Related posts

Leave a Reply

1 comment

  1. When a browsers finds a script tag, it executes the content directly. Because you put this code into your header page, this is executed before the html is generated, so before your menu finally exists.

    You have two solutions :

    1. Place your script tag at the end of the page, after your menu declaration
    2. Better way : execute your script when page has finished loading :

      $( document ).ready(function() {
          $('#menu-product-categories .sub-menu').hide(); //Hide children by default
      
          $('#menu-product-categories li a').click(function(event){
              if ($(this).next('ul.sub-menu').children().length !== 0) {     
                  event.preventDefault();
              }
          $(this).siblings('.sub-menu').slideToggle('slow');
          });
      });
      

    ready is an event, fired when all the DOM has been fully loaded.

    Corresponding jQuery documentation : http://api.jquery.com/ready/