I am working on selection mode in my app (selecting multiple elements to execute some action). It works like this: at default you have a list of elements (decks) which are <a>
HTML elements. So, if you click one, it will redirect you to the specific page. There is also a “Select mode” button on the page. After clicking it, redirection is turned off (event.preventDefault
), instead selected items are added to an array (selectedDecks
) and styling is changed.
The problem is that I do not know how to remove the event listener when I exit selection mode. It still changes the styling etc. instead of redirecting.
Here is the function for toggling between selection mode on/off:
Here is function for toggling between selection mode on/off (I used ‘deck.removeEventListener('click', () => handleDeckClick(event, selectedDecks));
‘ here but it does not work):
function toggleSelectionMode() {
selectionMode = !selectionMode;
let selectedDecks = [];
if (selectionMode) {
selectionModeElements.decks.forEach(deck => {
deleteSelectedDecksButton.style.transform = "scale(1)"
deck.style.opacity = "50%";
deck.addEventListener('click', () => handleDeckClick(event, selectedDecks));
});
} else {
selectionModeElements.decks.forEach(deck => {
deck.removeEventListener('click', () => handleDeckClick(event, selectedDecks));
deck.style.opacity = "100%";
let deckCheck = deck.querySelector(".deck-check");
deckCheck.style.transform = "scale(0)";
deck.deckSelection = false;
});
selectedDecks = [];
deleteSelectedDecksButton.style.transform = "scale(0)";
}
}
and here is the function for handling clicking a deck (executed as an eventListener):
function handleDeckClick(event, selectedDecks) {
event.preventDefault();
let deck = event.currentTarget;
let deckCheck = deck.querySelector(".deck-check");
let deckSelection = deck.deckSelection || false;
if (deckSelection === false) {
deck.style.opacity = "100%";
deckCheck.style.transform = "scale(1)";
selectedDecks.push(deck.getAttribute('data-deck-id'));
deck.deckSelection = true;
} else {
deck.style.opacity = "50%";
deckCheck.style.transform = "scale(0)";
const indexToRemove = selectedDecks.indexOf(deck.getAttribute('data-deck-id'));
if (indexToRemove !== -1) {
selectedDecks.splice(indexToRemove, 1);
}
deck.deckSelection = false;
}
}
Do you have any ideas about what I could use instead of deck.removeEventListener('click', () => handleDeckClick(event, selectedDecks));
? Is there a way to simply remove all event listeners from the element without specifying them? Or perhaps I should approach the entire selection mode differently? Thanks for your replies in advance.