Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show menu and hide it when clicking somewhere else?

Tags:

html

jquery

I have this scenario where I have body tag which doesn't visually wrap all content

And I have 3 TR's that contains 2 TD's - one for the info word and one for a yellow div.

Clicking on each Info TD - opens a div (of it's own - position absolute).

  • when I click the Info the yellow windows toggles.

enter image description here

The problem which I have : closing the yellow div.

I want it to be closed only when I click either in the relevant Info TD OR outside the yellow div

enter image description here

As you can see clicking the Info TD already closes the div.

But I have problem with the outisde area of the yellow div.

this is what I've done :

$("body").on('click', ".tdInfo", function (e) //when clicking on tdInfo
{
    var $cached = $(this).closest('tr').find('.myDiv'); //cache the suppose to be open div
    var wasOpen = $cached.is(":visible");
    $(".myDiv:visible").hide(); //hide all previous visible
    if (wasOpen) $cached.slideUp();
    else
   $cached.slideDown(function ()  //when the yellow div open - register once to close only when :not(.myDiv) are clicked
    {
        $("body").one('click', ':not(.myDiv)', function (e2)
        {
            e2.stopImmediatePropagation(); // Parent - ignore me.
            $cached.slideUp();
            return false;
        });
    });
});

Question

The code above doesn't work as expected. when I click on the yellow div - it closes. I don't want it to be closed.

The only situations where the yellow div should be close is when : clicking the TD Info or outside the yellow div.

Full working Jsbin

nb please don't try to change heights or insert another elements . this is the exact simplification of my current page. Also - I can find a solution with more JQ but I think it should be much simpler.

like image 251
Royi Namir Avatar asked Oct 31 '22 21:10

Royi Namir


1 Answers

I would do it like this

$(document).on('click', function(e) {
    if ( $(e.target).closest('.td').length > 0 ) return;

    var $cached = $(e.target).closest('tr').find('.myDiv');
    var wasOpen = $cached.is(":visible");

    $(".myDiv:visible").hide();

    if ($cached.length && (!wasOpen)) {
        $cached.slideDown();
    }
});

The body element is an element with a given height and width, as shown in the OP's example, and when clicking outside the yellow elements and outside the body you're clicking nothing, but all clicks will propogate to the document level so you have to listen on the document, not the body.

FIDDLE

like image 70
adeneo Avatar answered Nov 15 '22 17:11

adeneo