2

I need a drop-down menu when i click more options like Google. It's working but when I click outside the div it's inactive. I want to toggle the menu when I click outside of the div.

My javascript:

$('#other').click(function() {
    $(this).toggleClass('active');
    $(this).next('.dropdown').toggle();
    return false;
});
$('.dropdown a').click(function() {
    return false;
});
Joe
  • 15,205
  • 8
  • 49
  • 56
marvan
  • 31
  • 3
  • 13
  • Can you give us a fully working example (or not working) with what you tried so far. A jsfiddle would be nice. The script by itself, dont give us to much to work with. Only to guess. – gmo Aug 02 '13 at 12:54
  • this link [jsfiddle demo](http://jsfiddle.net/marvanjaam/8dczj/) – marvan Aug 02 '13 at 13:03

2 Answers2

0

You can subscribe to document.click and close the menu in the event handler. Stop the propagation of the event from the drop down so it doesn't close when clicking inside the drop down menu.

$('.dropdown').click(function (event) {
    event.stopPropagation();
    return false;
});

$(document).click(function (event) {
    if ($('.dropdown').is(':visible')) {
        $('.dropdown').toggle();
        $('#other').toggleClass('active');
    }
});

Your fiddle updated.

Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
  • But with that... each time you click on the document, the toggle event it's goint to trigger... even if you click outside and the menu is close... will be opened. – gmo Aug 02 '13 at 12:56
  • Probably want to use `.hide()` and `.removeClass('active');` on the document click handler. Otherwise clicking anywhere else on the page will open and close the dropdown. – Travesty3 Aug 02 '13 at 12:56
  • @Konstantin yeah bro. it's working. but where ever you click in page the drop-down menu coming. but i want when i click on the other that time only i want active show the drop-down menu – marvan Aug 02 '13 at 13:07
  • @marvan I have updated with a check whether the drop down menu is currently visible. – Konstantin Dinev Aug 02 '13 at 13:11
  • @marvan According to what you've written the code does exactly what you've described. – Konstantin Dinev Aug 02 '13 at 13:22
0

Got an idea from this answer

$(document).mouseup(function (e)
{
    var container = $("#other");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.toggle();
    }
});

My thought, it should not toggle, better you show/hide mechanism.

Community
  • 1
  • 1
Praveen
  • 55,303
  • 33
  • 133
  • 164