1

I'm trying to do something like submenu on input click and close it on losing focus with jQuery. Only accomplished using mouseup like this:

$(document).mouseup(function (e){

   var container = $(".container");

   if (!container.is(e.target)
       && container.has(e.target).length === 0
       && !$(".input").is(e.target))
   {
       $('.submenu').removeClass('submenu');
   }
});

here is my results: http://jsfiddle.net/Lwfhbdmp/8/

this works OK, but I think it's too complex and maybe there is a simpler solution for this? Please help.

user1844923
  • 179
  • 1
  • 11

1 Answers1

1

jsFiddle demo

A cleaner solution:

$(function(){

    var $submenu,
        contHov = 1,
        $container = $('.container').hover(function(){ contHov^=1; }); // Tog flag on hover

    $(document).on('mouseup keyup', function( e ){
        if(contHov||e.which==27) $submenu.removeClass("submenu");
    });

    $(".input").on("click", function(e){
        $submenu = $(this).closest("div").toggleClass('submenu');
    });

    // That's it. From now on, whenever you desire to
    // reference to the currently active 'submenu'
    // simply use the $submenu variable:

    $(".btn-inside").on("click", function(){
        alert("Clicked");
        $submenu.removeClass("submenu");
    });

});

...and you can even use ESC to close the $submenu

How to close-hide DIV clicking outside of it (but not inside)

Community
  • 1
  • 1
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313