Reputation: 1130
I am making a custom modal and I have a HTML structure with an overlay and within the overlay I have the modal with a close button like this:
<div class="overlay close-project">
<div class="modal">
<button class="close-project">Close</button>
</div>
</div>
Within the modal and on the overlay itself I added a class called close-project
which is supposed to close the modal. The principle is that when the user clicks on the overlay(background) or the cross itself, both do the same action (Which is closing the modal ofcourse)
The only problem I have with my current code is that when I click on the outside (The overlay) the closeProjectModel function gets triggered 1 time and returns null. But if I click on the cross within the modal the event gets triggered 2 times and returns the data within data-target-project
as well as null. How can I stop that from happening? So either way the event only get's triggered 1 time and closes the modal
<div class="overlay close-project">
@for ($i = 0; $i < 6; $i++)
<div class="modal project-card project-{{ $i + 1 }}" data-target-modal="{{ $i + 1 }}">
<div class="p-6">
<div class="font-bold text-xl mb-2">The Coldest Sunset {{ $i + 1 }}</div>
<p class="text-gray-700 text-sm md:text-base lg:text-base xl:text-base">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus quia, nulla! Maiores et perferendis eaque, exercitationem praesentium nihil.
</p>
</div>
<button class="close-project" data-target-project="{{ $i + 1 }}">×</button>
</div>
@endfor
</div>
function closeProjectModal($project) {
alert($project)
let destination = $('.project-' + $project);
destination.removeClass('animate__animated animate__zoomIn animate__faster').addClass("animate__animated animate__faster animate__zoomOut");
setTimeout(function () {
destination.addClass("hidden");
destination.removeClass("animate__animated animate__faster animate__zoomOut");
$('.overlay').delay(300).addClass('hidden')
}, 300)
$('html body').removeClass("overflow-hidden");
}
$(document).on('click', ".close-project", function() {
if($(this).data('target-project')) {
closeProjectModal($(this).data('target-project'))
} else {
closeProjectModal(null)
}
});
I already made the modals unique by adding a variable in the classname as well as in the data-targets so they can be easily distinguished. I have an feeling i'm thinking way to hard on this
Upvotes: 0
Views: 352
Reputation: 10765
Looks like the event is bubbling up to the overlay
, causing the 2nd
firing of the event
, event.stopPropagation()
inside your event handler
callback
may solve your issue:
$(document).on('click', ".close-project", function(e) {
e.stopPropogation(); //Stop the event from bubbling
if($(this).data('target-project')) {
closeProjectModal($(this).data('target-project'))
} else {
closeProjectModal(null)
}
});
Upvotes: 2