0

I have a simple dropdown menu that works nicely but is there a way so that if you click anywhere but the ul it will toggle it closed again?

Jquery

$('.header').click(function() {
    $('.menu').toggle();
});

HTML

<a class="header" href="#">All</a>
<ul class="menu">
    <li>All</li>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>
Jacinto
  • 558
  • 2
  • 9
  • 24

2 Answers2

1

I would change toggle to toggleClass and add an active or open class in your css. You can also use an animation if you're using the JQuery UI. e.g.

.menu {
display:none;
}

.menu.active {
display:block;
}

then

$('.header').click(function(e) {
  $('.menu').toggleClass("active", 1000);
  if (!$('body').hasClass("menu-active")) {
    $('body').addClass("menu-active");
  }
});

$('body.menu-active').click(function(e) {
  $('.menu').removeClass("active");
  $('body').removeClass("menu-active");
});
Christopher Marshall
  • 10,678
  • 10
  • 55
  • 94
0

How about adding:

$('.header').click(function(e) {
  e.stopPropagation();
  $('.menu').toggle();
});
$('body').click(function() {
  $('.menu').hide();
});

jsFiddle example.

j08691
  • 204,283
  • 31
  • 260
  • 272