Reputation: 11104
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
).
Upvotes: 1
Views: 6650
Reputation: 69905
Check if the target
is not the close link inside the form-window
click
handler. It not stop the event
propagation
else let the document click
handler take care of rest. Try this
$(document).live('click',function(){
$('#form-window').removeClass('show');
});
$('#form-window').live("click",function(e){
if(!$(e.target).is('a.close')){
e.stopPropagation();
}
});
Upvotes: 5
Reputation: 78650
Just add an additional handler to the close button which also closes the window.
$(".close").live('click',function(){
$('#form-window').removeClass('show');
});
Ideally you probably want to actually add the .close
selector in addition to document
and only have the function once to avoid code duplication.
Upvotes: 2