Tallboy
Tallboy

Reputation: 13407

How to hide a menu on anything but a click on the menu

I have a link which is a persons username. When you click it, a little flyout window (an unordered list) appears. I'm trying to make it so:

  1. Clicking on the persons username toggles the flyout ul with fadein/out
  2. If you click to show the flyout, and click ON the ul, it doesnt disappear
  3. if you click on the body anywhere except the flyout, it disappears

This is what I have so far but I'm basically just fooling myself into thinking I know what I'm doing :(

$(document).ready(function() {
    $('.flyout h3 a').click(function() {
        var flyout = $('.flyout ul');
        flyout.fadeToggle(80,function() {
            if ( flyout.is(':visible') ) {
                console.log('visible');
                $(document).on('click',function(e) {
                    flyout.fadeOut(80);
                    e.stopPropagation();
                });
            } else {
                $(document).off('click');
            }
        });
    });
});

html:

<div class="flyout">
                <h3>Welcome back, <a href="#">Dogbreath</a><img src="img/down-arrow.png" alt="dropdown"></h3>
                <div class="menu">
                    <ul>
                        <li><a href="#"><span class="icon">&#128101;</span>Users</a></li>
                        <li><a href="#"><span class="icon">&#128360;</span>Groups</a></li>
                        <li><a href="#"><span class="icon">&#9881;</span>Configuration</a></li>
                        <li><a href="#"><span class="icon">&#59201;</span>Logout</a></li>
                    </ul>
                </div>
            </div> 

Upvotes: 0

Views: 324

Answers (1)

sbeam
sbeam

Reputation: 4892

you are trying to do too much in the callback function for fadeToggle()

try just having something like this (untested)

$flyout = $('.flyout ul');
$('.flyout h3 a').click(function() { $flyout.fadeToggle(80) }

this takes care of hiding/showing the menu when the username is clicked, no?

then, separately and independently, bind events on document(this might take some tweaking)

// any click on document element that isn't a child of flyout, closes flyout
$(document).on('click',function(e) { if ($(e.target).parents($flyout).length == 0 $flyout.fadeOut() });

Upvotes: 1

Related Questions