I have this PHP that is helping me populate a script:
<script>
(function($){
<?php foreach($buttons as $button) { // loop throught all available buttons ?>
// by clicking button one
$('.button-1').click( function () {
// display:none to all filters but filter-1
$('.filter-2, .filter-3, .filter-4, .filter-5, .filter-6').css({display: "none"});
// guarantee filter-1 will be visible with display: block;
$('.filter-1').css({display: "block"});
});
<?php } ?>
})(jQuery);
</script>
But the numbers of buttons and filters (button-1, filter-2, and etc) are currently manually set, and I don't know how to build the logic, where
display:hide to all filters but 'filter-1' and display:block only to 'filter-1'display:hide to all filters but 'filter-2' and display:block only to 'filter-2'How can I build this logic?
Don't do it in a loop. Give all the buttons a common class button, and add a handler to all of them. This can then get the specific button number from an attribute, and use that in the code to determine which filter to display.
So the HTML for the buttons will be something like this:
<button class="button" data-filter="1">Filter 1</button>
<button class="button" data-filter="2">Filter 2</button>
and so on
and the HTML for the filters will be:
<div class="filter-1 filter">blah</div>
<div class="filter-2 filter">lorum ipsum</div>
and so on
Then your jQuery code will simply be
$(".button").click(function() {
let filternum = $(this).data("filter");
$(".filter").hide();
$(`.filter-${filternum}`).show();
}
This adds the handler to all the buttons at once.