the function working well, but when I click on first element and second element then first once again, He skips the highlight and moves to the second event, remove direct.
HTML
<button class="cancelBtn">Cancel highlighting</button>
<div>
<a href="#" class="btn">Button</a>
<a href="#" class="btn">Button</a>
<a href="#" class="btn">Button</a>
<a href="#" class="btn">Button</a>
<a href="#" class="btn">Button</a>
<a href="#" class="btn">Button</a>
</div>
<style>
.btn.click {
background-color: red;
}
</style>
JS
function doubleClickEvenElements(eventElements, cancelHighlightingElement) {
eventElements.forEach(eventElement => {
let count = 0;
eventElement.addEventListener("click", element => {
element.target.classList.add("element");
eventElements.forEach(ele => {ele.classList.remove("click");});
element.target.classList.add("click");
count++;
if (count == 2) {
element.target.remove();
count = 0;
};
});
cancelHighlightingElement.addEventListener("click", btn => {
count = 0;
eventElements.forEach(ele => {ele.classList.remove("click");});
});
});
};
let eventElements = document.querySelectorAll("div .btn");
let cancelHighlighting = document.querySelector(".cancelBtn");
doubleClickEvenElements(eventElements, cancelHighlighting);
you can try the code on CodePen
in the second click on the element, I need it to make highlight first then next click will delete it from DOM, but it deletes direct without highlight first.
I'm sorry about my bad explain, I hope you are understanding what I'm saying 😺.
This is because you never reset the count
variable of a clicked button when another one is clicked, so the second time you click a button, the count
value will be directly 2.
To fix this I would advise you to use the "click" class as an indicator if the button has been clicked or not. You will then only have to check if the class of the clicked button is present, and if so delete it (and add the class if not)
To check if an element has the class you can use:
const isClicked = element.target.classList.contains("click")
You would need to do this check before removing the "click" class on all the elements