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).
Info
the yellow windows toggles.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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With