Reputation: 826
I'm trying to create a basic modal myself and I'm having a little bit trouble here (maybe it's because I'm an expert working with jQuery - don't take it seriously).
I have this HMTL markup:
<div id="modal-boxes">
<div id="modal-updates" class="modal-content">
Content for modal box here.
<a href="#" class="close-modal">Close</a>
</div>
</div>
<div id="modal-mask"></div>
So, I made a function that tells the modal box to close and to make disappear the #mask div. And another one to when I click outside of it, it closes anyway. In other words, clicking outside the #modal-updates div is the same that clicking on close button. But the problem is that when I want to click inside the #modal-updates div (should not disappear) it closes anyway. Here is my javascript code:
$(".modal").click(function(e){
e.preventDefault(); // Cancel the default link behavior
$("#modal-mask").fadeTo(400, 0.4);
$("#modal-boxes").fadeIn();
var getName = "#" + $(this).attr("name");
$(getName).fadeTo(400, 1);
});
function closeModal() {
$("#modal-mask, #modal-boxes").fadeOut();
}
$(".close-modal").click(function(e){
e.preventDefault();
closeModal();
});
$(".modal-content").click(function(){
closeModal();
});
Any help?
Regards, Tiago Castro
Upvotes: 2
Views: 3948
Reputation: 3270
Try:
$('#modal-updates').click(function(e) {
e.stopPropagation();
});
If done right, this will stop $("#modal-boxes").click()
from triggering.
[edit] fixed a typo and added link to jsFiddle with it working
Upvotes: 3
Reputation: 5494
Why not using the modal dialog of jQuery?
About your example :
1) for the link I prefer to do something like:
<a href="javascript:void(closeMyPopup());" class="close-modal">Close</a>
That way no need to deal with things like preventDefault or click event
2)I guess that instead of binding your click event to ".modal-content" you wanted to bind it to "#modal-mask" ;)
Upvotes: 0