CSS: Failing to display unless refreshed - Navigation bar

I have been working on navigation bar and the strangest issue is occurring.
Please use the JSFiddle link to see what I mean.

To duplicate the error:

  1. Run the code when the desktop view is active i.e. when the navigation links are in a line.
  2. Then resize the screen till the "click me" is displayed.
  3. Then press it.
  4. Now run the code while you see the "click me" and press it again.

JS information

jQuery(document).ready(function($) {
    // UserCP 
    $('.rotate').on('click', function() {
        $(this).toggleClass("down");
    });
    $('.nav-start').on('click', function() {
        $("#nav2").removeClass("hidden");
        $('#nav2 li a').stop().slideToggle('100');
        return false;
    });
    $(document).ready(function() {
        $('#nav2 li a').stop().slideToggle('100');
    });

    $('body').on('click', function() {
        $('#nav2 li a').stop().slideUp('100');
    });
    $("#nav2 li a").click(function(e) {
        e.stopPropagation();
    });
    $(document).click(function(event) {
        if (!$(event.target).closest('#nav2 li a').length) {
            if ($('#nav2 li a').is(":visible")) {
                $('html, body').on('click', function() {
                    $('#nav2 li a').stop().slideUp('100');
                });
            };
        };
    });
});

FIXED - UPDATED JSFiddle! Thanks @Louys Patrice Bessette @Titus @Rick

Answers 1

  • You are using two click events on this "Click me" li...
    (One on .navstart and one on .rotate)
    It may not be an issue, but this make the code harder to read.

    Then, when you slideToggle(), if you want the submenu to slide down, it has to be hidden.
    Because, since you remove the hidden class (probably usefull on load), the submenu is visible.
    A Toggle hides it.

    I simplified your script to this.
    Have a look at this updated Fiddle.

    $(document).ready(function() {
    
      // Show submenu on "Click me"
      $('.nav-start').on('click', function() {
        $('.rotate').toggleClass("down");
        $("#nav2").removeClass("hidden");
        var subNav = $('#nav2 li a');
    
        if(subNav.css("display")=="block"){
          subNav.stop().slideUp('100');
        }else{
          subNav.stop().slideDown('100');
        }
      return false;
      });
    
    
      $("#nav2 li a").click(function(e) {
        e.stopPropagation();
      });
    
      // Hide submenu on document click
      $(document).click(function(event) {
        if (!$(event.target).closest('#nav2 li a').length && $('#nav2 li a').is(":visible")) {
          $('#nav2 li a').stop().slideUp('100');
        };
      });
    });
    

Related Articles