Final working code based on accepted answer
$('#photo-upload, #photo-upload .close').click(function(){
$('#photo-upload').removeClass('show');
});
$('#upload-button').click(function(){
$('#photo-upload').addClass('show');
});
$('#form-window').click(function(e){
e.stopPropagation();
});
original question
I have a modal window with a close button. The window is triggered by a link a#upload-button. #photo-upload is a 100% height + width fixed div. #form-window is a 200px by 200px box that is centered horizontally and vertically inside of #photo-upload
<div id="photo-upload">
<div id="form-window">
<!-- Content -->
<a class="close"></a>
</div>
</div>
The close button is absolutely positioned a little bit beyond the upper right corner. I want to set a click function so that clicking outside the modal window closes the window, and also so that clicking on the close button closes the window. But so that clicking on the window itself does not close the window.
My current code is:
$('#photo-upload').click(function(e){
if(!$(e.target).is('#form-window')){
return false;
} else {
$(this).removeClass('show');
}
});
$('#form-window').live("click",function(e){
if(!$(e.target).is('a.close')){
e.stopPropagation();
}
});
$('#upload-button').live("click", function(){
$('#photo-upload').addClass('show');
});
$('#photo-upload .close').live("click", function(){
$('#photo-upload').removeClass('show');
});
With the above code, nothing happens when I click any of those elements, and can’t close the div. What am I doing wrong?
How do I use stopPropagation() on a parent but exclude a child element (in my case, a.close).
Just add an additional handler to the close button which also closes the window.
Ideally you probably want to actually add the
.closeselector in addition todocumentand only have the function once to avoid code duplication.