Reputation: 1790
I am trying to set up a system so that when a user clicks, if that click did not originate from within a specified div then a function should be fired that will do something with that div. Basically more when a user clicks outside of a div i want to hide it, but the problem is that i have a few elements that i want to do this with, so event.stopPropagation doesn't work very well.
document.onclick = function (e) {
e = !e ? window.event.srcElement : e.target;
if ($('#toppanel div#panel').not(e.id).is(':visible')) { $('.dashboardNav .addWidget').click(); }
if ($('#TrackRibbon').not(e.id).is(':visible')) { $('.dashboardNav #openRibbon').click(); }
if ($('.subnav').not(e.id).is(':visible')) { $('.subnav').hide(); }
}
but this doesn't work as i want either yet, it does somewhat, but i have multiple .subnav on the page and with this you can open all of them without the others closing.
any ideas on how to accomplish a goal like this would be greatly appreciated, also if i didnt explain well enough just let me know.
Upvotes: 1
Views: 775
Reputation: 3538
Would something like this work?
$(document).bind('click', function(e) {
if($(e.target).hasClass('dontTriggerThisFunction')) { return; }
doTheStuffWeWantToDo();
});
Upvotes: 2
Reputation: 1790
So this is how i managed to accomplish most of what I wanted. I think with a few tweaks it will be good.
$(document).click(function (e) {
var closables = ["#TrackRibbon", '#toppanel', '.subnav', '#Mailbox'];
var toggles = ['#openRibbon', '.addWidget', '.topnav > li', '#MailboxToggle'];
var skip = -1;
e = !e ? window.event.srcElement : e.target;
for (var j = 0; j < toggles.length; j++) {
if ($(e).parent(toggles[j]).length > 0 || $(e).is(toggles[j])) {
skip = j; continue;
}
}
for (var k = 0; k < closables.length; k++) {
$(closables[k]).each(function (i) {
if (skip !== k) {
if ($(this).has($(e)).length === 0 && $(this).is(':visible')) {
$(this).hide();
}
}
});
}
});
The only part that doesn't work quite right is the '.subnav' which there can potentially be a lot of. So if anyone has any suggestions to improve let me know.
Upvotes: 0