Very Curious
Very Curious

Reputation: 891

JQuery, how to make div disappear when clicked anywhere out of it?

I am trying to achieve the following behavior:

When link "Option" with DivA id is clicked, the DivB should show up with fade in effect. If I click the link "Option" again as well as if clicked anywhere else in the page except of the DivB inside, the DivB should dissapear again.

This is my HTML code:

<a href="..." id="DivA">Option</a>
<div id="DivB">
  <ul>
    <li>A</li>
    <li>B</li>
    <li>C</li>
  </ul>
</div>

This is my JQuery code. It is wrong, if the DivB is hidden and I click anywhere in the document, the DivB appears.

<script type="text/javascript">
    $(document).click(function () {
        $("#DivB").fadeToggle("200");
    });
    $("#DivA").click(function () {
        e.stopPropagation();
        return false;       
    });
</script>

Where's the mistake? Thanks for help.

Upvotes: 2

Views: 3623

Answers (4)

Qasim Nadeem
Qasim Nadeem

Reputation: 607

    $(document).mouseup(function(e) {
        var container = $("your selector here");
    
        // if the target of the click not the container or not a descendant of that container
        if (!container.is(e.target) && container.has(e.target).length === 0) {
            container.hide();
        }
    });

Upvotes: 0

MackieeE
MackieeE

Reputation: 11862

<script>
    $(document).on('click', function( evt ) {
        evt.stopPropagation();
        if ( evt.target.id == 'DivA' || $('#DivB').is(':visible')) 
             $('#DivB').fadeToggle();
    });
</script>

Fiddle: http://jsfiddle.net/nR6e3/1/

Upvotes: 1

mplungjan
mplungjan

Reputation: 177940

Live Demo

$(function() {
  $(document).on("click",function (e) {
     if (e.target.id=="DivA") {
       $("#DivB").fadeToggle(200);
       e.stopPropagation();
       return false;
     }
     else if ($("#DivB").is(":visible")) {
       $("#DivB").fadeOut(200);
     }
  });
});

Upvotes: 4

Viswanath Donthi
Viswanath Donthi

Reputation: 1821

$(document).on("click",function () {
   if ($("#DivB").is(":visible")){
       $("#DivB").fadeOut(200);
   }
});

$("#DivA").click(function (e) { // you need place 'e'(for event handling)
    $("#DivB").fadeIn(200);
    e.stopPropagation();
    return false;       
});

Upvotes: 0

Related Questions