0

I have this code to toggle the ul visibility.

$('.cliackable').click(function(){ $(this).find('ul').toggle(); });

$('.cliackable').click(function(event) {
    event.stopPropagation();
});

How do I toggle this when user clicks outside the ul?

I tried using the answer here but to no avail : jQuery toggle hide on click elsewhere

Update

my CSS looks like this

<!-- language: css -->
html, body {height:100%;width:100%;margin:0;}
#navigation-main {width:65px;margin-left:10px;}
#navigation-main .sf-menu-main li ul {display:none;}
#navigation-main .sf-menu-main li li {background:#e73420;border-top:1px solid rgba(0,0,0,0.1); width: 235px; clear:both; padding:5px 0px 5px 15px; color:#fff;}
#navigation-main .sf-menu-main li li a {width: 250px; padding:5px 10px 5px 15px; color:#fff;}

and the html

<div id="navigation-main">
    <ul class="sf-menu-main">
        <li style="color:#fff;" class="clickable">
            Menu
            <ul>
                <li>
                    <a class="login-head-font" href="">Home</a>
                </li>
                <li>
                    <a class="login-head-font" href="">Events</a>
                </li>
            </ul>
        </li>
    </ul>
</div>

I tried using your js but didnt work

Community
  • 1
  • 1
Md Nauman Khalid
  • 15
  • 1
  • 1
  • 3

2 Answers2

1

Is this you expected?

http://jsfiddle.net/utgc0981/2/

HTML

<div id="navigation-main">
    <ul class="sf-menu-main">
        <li class="clickable">Menu
            <ul class="sf-menu-sub">
                <li> <a class="login-head-font" href="">Home</a>

                </li>
                <li> <a class="login-head-font" href="">Events</a>

                </li>
            </ul>
        </li>
    </ul>
</div>

JS

$(function () {
    var sf_menu_sub = $('.sf-menu-sub');
    $('.clickable').on('click', function (e) {
        e.stopPropagation();
        sf_menu_sub.toggle();
    });
    $(document).on('click', function (e) {
        sf_menu_sub.hide();
    });
});
kechol
  • 1,554
  • 2
  • 9
  • 18
  • perfect!! works seemlessly .. just one more query.. what if i have two similar menus ? should create two different scripts for both or is there a way around in the same cause if i click on one both ul get showed up – Md Nauman Khalid Sep 21 '14 at 08:44
-1

Check for $(e.target) . If it is anything else except the ul or if it is the body then hide it else show it.

Demo: http://jsfiddle.net/lotusgodkk/GCu2D/344/

JS:

$(document).ready(function () {
    $('.checked').click(function (e) {
        $('ul').show();
    });
    $(document).on('click', function (e) {
        if ($(e.target).is('body')) {
            $('ul').hide();
        }
    })
});
K K
  • 17,794
  • 4
  • 30
  • 39