How to perform action when a click happens outside of specified elements

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.

Answers


Would something like this work?

$(document).bind('click', function(e) {
  if($(e.target).hasClass('dontTriggerThisFunction')) { return; }

  doTheStuffWeWantToDo();
});

Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.