I’m slowly getting better at JS. I’ve been going through my projects and condensing code will I have a lot of repetition. I am using JS for an event listener on 3 different cards. I have on ‘click’ handled but I also had code for ‘keydown’ events. Here is what I had repeated for each of the 3 cards:
flip1.addEventListener('keydown', function (e) {
if (e.code !== 'Tab') {
e.preventDefault();
flip1.classList.toggle('show-answer');
}
});
I have variables for the 3 cards called flip1, flip2, flip3 - each is using the element ID.
I managed to reduce the 3 codes blocks into the following:
const cardsId = [flip1, flip2, flip3];
cardsId.forEach(function(card) {
card.addEventListener('keydown', function (e) {
if (e.code !== 'Tab') {
e.preventDefault();
card.classList.toggle('show-answer');
}
});
});
But I wanted to reduce it to a ternary operator and that is where I am having problems. I tried this:
cardsId.forEach(function(card) {
card.addEventListener('keydown', () => card.classList.toggle('show-answer'));
});
And that works except for the TAB and SPACEBAR keys. So I tried using a ternary operator but I don’t know what to use for the else condition. Here is an example of one thing I tried:
cardsId.forEach(function(card) {
card.addEventListener('keydown', (e) => e.code !== 'Tab' ? e.preventDefault() && card.classList.toggle('show-answer') : true);
});
No keydown events work for that. If you think the first forEach block is fine, then I’ll just stay with that, but it seems like a ternary statement would work here.
The cards are on my portfolio page which I will link below, but I’m still working locally so the changes I’ve made are not in the live JS file yet. Any ideas? Here is the page: James Kernicky Portfolio