Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Hide a div menu after clicking outside div

I've build a drop down menu at:

http://www.ourbridalsongs.com/new_header/header.php

When you click on the up/down arrow next to the logo - the menu appears - I'd like to make it disappear when clicking anywhere else on the screen - for some reason it's getting stuck and doesn't slide back up.

Can anyone help resolve this!

Here's my script:

$(document).ready(function () {

    $("ul.subnav").parent().append("<span></span>");
    $("ul.topnav li span").click(function () {
        $(this).parent().find("ul.subnav").slideDown('slow').show();
        $(this).parent().click(function () {}, function () {
            $(this).parent().find("ul.subnav").slideUp('slow');
        });
    }).hover(function () {
        $(this).addClass("subhover");
    }, function () {
        $(this).removeClass("subhover");
    });

});

Thanks!!!

like image 369
Simon Avatar asked Aug 23 '10 01:08

Simon


People also ask

How do I hide menu on click outside?

Answer: Use the jQuery on() method You can use the jQuery click() method in combination with the on() method to hide the dropdown menu when the user click outside of the trigger element.

How do you hide a div after clicking it?

To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element. The onclick listener for the button will have a function that will change the display attribute of the <div> from the default value (which is block ) to none .

How do you hide a div when the user clicks outside of it using Javascript?

To hide an element when clicked outside: Add a click event listener to the document object. On each click, check if the clicked element is outside of the specific element using the contains() method. If the clicked element is outside, hide the original element.


2 Answers

It's quite simple: bind a function that hides that menu to everything except that menu. To do that bind a click listener to the body element as it's everywhere, also bind a click listener to menu - the last one should just prevent from executing the first one.

$("body").click(function() {
    $("#services-container-id").hide();
});

$("#services-container-id").click(function(e) {
    e.stopPropagation();
});
like image 157
Crozin Avatar answered Oct 10 '22 04:10

Crozin


add this snippet in your code

$(document).click(function(e){
    var myTarget = $(".subnav");
    var clicked = e.target.className;
    if($.trim(myTarget) != '') {
        if($("." + myTarget) != clicked) {
            $("ul.subnav").slideUp('slow').hide();
        }
    }
});

this will close your ul.subnav when you click anywhere in your document.

like image 6
rob waminal Avatar answered Oct 10 '22 03:10

rob waminal