Been trying to figure this out for a few days and I believe the issue has to do with event delegation, but I’m unsure how to solve it.
I have a website that loads a list of employees from the database. Each employee is placed in a card and when the card is clicked, a modal appears with additional information about the employee.
There are different departments, so in a top menu I dynamically load the department list from the database. I can then click on a department and use AJAX to only display the employees from the selected department. It looks exactly the same as the initial load, however the modal doesn’t work. When I look at the dev tool, I can see the data loaded for the department. Everything needed is loaded, except the modal will not open.
I can use the inspector to see the information is all loaded correctly, but I think the issue is that it was loaded to the page without a refresh.
I even tried to place the javascript in the get_organization_data.php in hopes it would work – but it didn’t.
Any thoughts?
//Open modal when clicking on employee card
document.addEventListener("click", (e) => {
if (e.target.matches(".employee_card")) {
details.classList.remove("hidden");
details.classList.add("overlay");
}
});
//Close modal when clicking on overlay
document.addEventListener("click", (e) => {
if (e.target.matches(".overlay")) {
details.classList.remove("overlay");
details.classList.add("hidden");
}
});
These are the AJAX calls
$(document).on("click", ".org", function () {
id = $(this).attr("id");
// alert(id);
$.ajax({
url: "logic/get_organization_data.php",
method: "POST",
data: {
id: id,
},
success: function (data) {
$(".main_section").html(data);
// $(".employee_modal").html(data); //thought this may be needed?
},
});
});
$(".main_section").on("click", "a", function (event) {
event.preventDefault();
id = $(this).attr("id");
// alert(id);
$.ajax({
url: "logic/get_employee_data.php",
method: "POST",
data: {
id: id,
},
success: function (data) {
$(".employee_modal").html(data);
},
error: function () {
alert("Error");
},
});
});