Jquery addClass to wp_nav_menu is very slow

I have added a li class to my wp_nav_menu with the following simple code

$('#menu-navigasjon').children('li').addClass('liparent');

When you visit my site http://annalidesign.com, WordPress will first generate the original navigation menu (vertical) without liparent class, and a split millisecond after that the Jquery code will run and add on the “liparent” class making it horizontal as I want.

Read More

The problem is that I can see how the navigation looks a split second before the new liparent class is added. Is there anything I can do to avoid this happening? I’ve tried to paste the Jquery script right after the HTML for the navbar, but the original vertical navigation bar still shows a split millisecond before.

I’ve tried using walker function, using the following code without any luck, because I don’t know how to ADD classes to the existing li element that WordPress generates. My code removes all the li classes WordPress generates and only adds one class. That is not what I want.

  class MyWalker extends Walker_Nav_Menu {

   function start_lvl(&$output, $depth) {
     $indent = str_repeat("t", $depth);
     $output .= "n$indent<ul class="sub-menu">n";
   }

function start_el(&$output, $item, $depth, $args) {

       if($depth == 0) {
          $class_names = ' class="liparent"';
       }

       $output .= $indent . '<li' . $class_names . '>';
    }
}

Related posts

Leave a Reply

1 comment

  1. You could hide the menu initially then use jQuery to show it once the addClass function has run. Here’s a stripped-down test case that uses setTimeout to simulate a page loading before jQuery runs Codepen: http://codepen.io/SteveClason/pen/eZqBrw):

    HTML

    <div class="nav">
      <div class="ulwrap">
        <p>This one doesn't blink.</p>
        <ul id="menu-navigasjon">
          <li>Item 1</li>
          <li>Item 2</li>
          <li>Item 3</li>
          <li>Item 4</li>
          <li>Item 5</li>
        </ul>
        <p>But this one does.</p>
        <ul id="menu-navigasjon2">
          <li>Item 1</li>
          <li>Item 2</li>
          <li>Item 3</li>
          <li>Item 4</li>
          <li>Item 5</li>
        </ul>
      </div>
    </div>
    

    CSS

    .liparent {
      color: red;
    }
    #menu-navigasjon {
      display: none;
    }
    

    JavaScript

    // This menu is initially hidden by CSS.
    $('#menu-navigasjon').children('li').addClass('liparent');
    $( '#menu-navigasjon' ).css( 'display', 'block');
    
    // This menu initially displays then is altered by JavaScript. There's a timer to simulate a page loading.
    function blink() {
      $('#menu-navigasjon2').children('li').addClass('liparent');
    }
    setTimeout( blink, 1000 );