Full code: https://codepen.io/vvaciej/pen/abPdEBN
Program rely on 8 food areas and there is 3 buttons that segregate them: breakfast, lunch and button all.
I did it by adding class active and hidden to every element
like there:
allButton.addEventListener('click', function () {
firstFoodElement.classList.add('active');
firstFoodElement.classList.remove('hidden');
secondFoodElement.classList.add('active');
secondFoodElement.classList.remove('hidden');
thirdFoodElement.classList.add('active');
thirdFoodElement.classList.remove('hidden');
fourthFoodElement.classList.add('active');
fourthFoodElement.classList.remove('hidden');
fifthFoodElement.classList.add('active');
fifthFoodElement.classList.remove('hidden');
sixthFoodElement.classList.add('active');
sixthFoodElement.classList.remove('hidden');
seventhFoodElement.classList.add('active');
seventhFoodElement.classList.remove('hidden');
eightthFoodElement.classList.add('active');
eightthFoodElement.classList.remove('hidden');
});
Code works like it should, but I know I would be punished as junior programmer so I want to do the same but more cleaner
Counting on your help
2
Answers
I would recommend rewriting the code to categorize ‘food’, ‘breakfast’, ‘lunch’, and ‘drink’ as classes. So, instead of using
<div class="first-food-display active">
, you could use something like<div class="food-display lunch-display active">
. This implies that this element would be displayed only when either the "all" or "lunch" buttons are selected.Following that, I’d suggest modifying the JavaScript in the following manner. I tested it on your codepen and it works.
Add some parameters to the buttons and to the
div
that will be filtered. For exampledata-filter
. And then use them.I would do something like this (this is just an example and I’m sure you can improve it):
P.S. The example also takes into account the situation when it can be both breakfast and lunch 😉