Hide dropdown on 'body' click produces to need double click to show again

Issue

I have this drop down menu that when one menu is clicked if there was another one active, this one is deactivated and then the new one is activated:

$('.idiomas span.current').toggle(function(){
                            //alert(true);
                            $('.idiomas span.clicked').next('ul').hide();
                            $('.idiomas span.clicked').removeClass('clicked');
                            $(this).next('ul').fadeIn();
                            $(this).addClass('clicked');
                           
                    },function(){
                            $(this).next('ul').hide();
                            $('.idiomas span.current:not(.clicked)').show();
                           
                            
                    
                });

Ok, until here is working fine, but then I wanted the menus to be hidden when user clicks outside the entire menu; figured out that on body click should work as I needed:

    $('body').bind('click', function(e) {
        if($(e.target).closest('.idiomas ul').length == 0) {
            // se ha clickado fuera del menu
            $('.idiomas ul').hide();
            $('.idiomas span.current').removeClass('clicked').show();
            $('.facebook').css('visibility','visible');
        }else{
            //dentro: no hacemos nada.
        }
    });

and it does hide, but I need to click twice in the next menu item to make its sub-menu visible,

Any idea why?

Solution

Here’s something that might help. Here is the JSFiddle for it: http://jsfiddle.net/aTqP5/

Basic gist to your problem is that toggle has 2 states, and when you click on the body, the element gets hidden but the toggle state is still in “show” and has to go to “hide” then back to “show” again, hence the clicking twice.

$(document).ready(function(){    
    $('.idiomas span.current').click(function(event){
        event.stopPropagation();
        if ( $(this).hasClass('clicked') ) {
            $(this).removeClass('clicked');
            $(this).siblings('ul').hide();
        } else {
            $('.idiomas span.clicked').removeClass('clicked').siblings('ul').hide();
            $(this).addClass('clicked');
            $(this).siblings('ul').fadeIn();
        }
    });

    $('body').click(function(event) {
        event.stopPropagation();
        if ( $('.idiomas span.clicked').length > 0 ) {
            $('.idiomas ul').hide();
            $('.idiomas span.current').removeClass('clicked');
        }
    });
});

Answered By – Calvin

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.