Below is an example of a JavaScript project in which a Description field goes into an edit mode when the edit button is clicked on. This reveals a hidden textarea, some tabs to switch between edit and preview markdown output, and save and cancel buttons are all revealed.
Once the description is saved or canceled which trigger it to "close" out of edit mode
Right now to get out of edit mode you have to click the save or cancel buttons in the image below.
I would like to auto-close when the user clicks outside of the edit mode sections. So a click anywhere that is not related to the edit mode would then fire my JavaScript code which "closes edit mode".
Something like....
If in edit mode{
if click on any selector that is not .edit-btn, .save-btn, .tabs, or edit-wrapper{
// call my close edit mode function
closeEditMOde();
}
}
All names and everything made up to quickly explain my goal.
How can I achieve this in JavaScript/jQuery?
Something clever like a simple utility function would be nice that took an array of selectors....
function ifAnyElemExceptTheseClickedOn(['.save-btn', '.cancel-btn', '#edit-wrapper', '.tabs']){
// if a click event happens anywhere that is not inside one of the passed
// in array of selector elements on the page, then perform an action
// if click is outside of any of thewse selectors, then run a callback function
}
Clicking any of the red boxes will result in nothing besides there own defined click events.
Clicking anywhere outside the red boxes will trigger/fire function call to my JS function.
UPDATE
I now have a simple demo here http://jsfiddle.net/jasondavis/gpyusv6a/ which I think will work for my needs if I can get rid of the JS error that is thrown when I click outside of the DIVs which give this:
Uncaught TypeError: Cannot read property 'match' of undefined
Demo:
<div id="edit-wrapper">edit mode section
<div id="edit-wrapper-inner">
edit mode inner section
</div>
</div>
$(document).click(function(event) {
var target = $(event.target);
console.log(target);
if (!target.attr('id').match(/^edit-wrapper/).length && target.parents('#edit-wrapper').length == 0) {
console.log('Hide edit-wrapper because you clicked on the screen outside of the #edit-wrapper DIV');
$('#edit-wrapper').hide();
}
});

if ( $(e.target).closest('#edit_box').length === 0 ) close_edit_box()<body>and leave edit mode if in edit mode and stop propagation, else let it propagate (?)Uncaught TypeError: Cannot read property 'match' of undefinedit's close to working though thanksclosest()starts with the current element, so you don't need a regex orparents()-> jsfiddle.net/gpyusv6a/4