Search code examples
javascriptjqueryslidetoggle

Jquery menu Anchor onBlur event disables Div sub anchors


I am new to JQuery Development. I am facing a issue with the onblur event, while i am trying to make a custom menu for my website. could any one help me with this please.

Please find ths JS fiddle JS Fiddle

$(document).ready(function () {
    $('#showmenu').click(function (e) {
        e.preventDefault();
        this.focus();
        $('#serviceMenu').slideToggle("fast");
        $('#Contact').hide();
    });

    $('#showmenu').blur(function (e) {
        $('#serviceMenu').hide();
    });
});

The issue is that the show/hide div mechanism is based on a <a> tag. on clicking <a> the menu is toggling fine. i also want menu to toggle, when the user clicks anywhere outside the menu and the appearing div. In the fiddle i have added onblur() event for the anchor, that is making my sub links inside the div trigger onblur() event of main anchor, and hiding the menu. I tried to block event.propagation(), but its not working for me.


Solution

  • The problem here is, that the blur event is called, BEFORE you click on a#serviceMenu You also should learn how the event-propagation works: Direct and delegated events I updated your fiddle (with some comments): http://jsfiddle.net/M4LJh/7/

    $(document).ready(function () {
        $('#showmenu').on('click', function (e) {
            this.focus();
            $('#serviceMenu').slideToggle("fast");
            $('#Contact').hide();
            return false;
        });
    
        // prevent clickEvent to bubble up to #showmenu
        $('#serviceMenu a').on('click', function(e){e.stopPropagation();});
    
        // hide #serviceMenu on bodyClick
        //    - anywhere but an element with propagation stopped event
        $('body').on('click', function (e) {
            $('#serviceMenu').hide();
            return false; // e.stopPropagtaion(); + e.preventDefault();
        });
    });