I have an alert box that has its own close button. I didn't know users would be placing multiple instances of it on a web page.
Currently, when the close button of an element is clicked, only the first instance gets hidden. I can't close the other one after that. When I click its close button, nothing happens.
I want to be able to click each element's close button to hide that element and have the ability to hide the elements one at a time. I feel like it has something to do with the THIS keyword, but I'm not sure.
Here's the HTML.
<div class="dcom-c__alert">
<div class="dcom-c-alert__icon">
<svg class="dcom-c-alert__icon--alert" aria-hidden="true" focusable="false">
<use xlink:href="/public/icons/cbds-icons-ui.svg#error-circle">
</use>
</svg>
</div>
<div class="dcom-c-alert__message">
<div role="alert" class="dcom-c-alert-copy">Alert: Due to the weather in NC, our branches are closed Tuesday 2/27/21.
<a href="#" class="dcom-c-alert__icon--message" aria-label="Learn more about this alert.">Learn more
<svg role="presentation" class="dcom-c-alert__icon--chevron" focusable="false"
width="20" height="20">
<use href="/public/icons/cbds-icons-ui.svg#chevron-right"
xlink:href="/public/icons/cbds-icons-ui.svg#chevron-right">
</use>
</svg>
</a>
</div>
</div>
<button class="dcom-c-close-alert-wrapper" aria-label="Close">
<svg class="cbds-c-icon cbds-c-iconButton__icon alert-close" focusable="true">
<use href="../../../public/icons/cbds-icons-ui.svg#close"
xlink:href="../../../public/icons/cbds-icons-ui.svg#close"></use>
</svg>
</button>
Here's my JavaScript code. Can anyone please help? Thank you.
const alert = document.querySelector('#dcom-c-alert');
const hideAlert = document.querySelector('.dcom-c-close-alert-wrapper');
function closeAlert() {
alert.classList.add('hide');
}
hideAlert.addEventListener('click', function () {
closeAlert();
});
hideAlert.addEventListener("keydown", e => {
// ADA: Next button activates with spacebar or enter key
if (e.key === " " || e.key === "Enter" || e.key === "Spacebar") {
closeAlert();
}
});
After reading this post, I gained some clarity and solved my own issue. The key was creating a temporary variable (alert, in my case) to hold the index of the current alert.
How can delete the clicked item using the click event if all items have the same Id
Here's my JavasScript:
alerts.forEach(alert => {
let alert = alerts[i];
closeButtons[i].addEventListener('click', function () {
alert.remove();
});
});