I am using the “Filter Elements” example from W3Schools for a page template so that the visitor can filter listings based on the number of bedrooms. The filter buttons are working correctly, however when you first load the page all of the listings are hidden. The “Show All” button is active, like in the W3Schools example, however you still have to click “Show All” before it will load the hidden content.
Here is the W3Schools example: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_elements
Here is my test page with the issue: https://lakewoodcampground.com/properties-test-page/
I need the page to load with all of the listings visible. Essentially starting with the “Show All” button active, which it is, but on page load the listings are hidden.
<div id="myBtnContainer">
<button class="btn active" onclick="filterSelection('all')"> Show all</button>
<button class="btn" onclick="filterSelection('one-bed')"> 1 Bedroom</button>
<button class="btn" onclick="filterSelection('two-bed')"> 2 Bedroom</button>
<button class="btn" onclick="filterSelection('three-bed')"> 3 Bedroom</button>
<button class="btn" onclick="filterSelection('four-bed')"> 4 Bedroom</button>
<button class="btn" onclick="filterSelection('five-bed')"> 5 Bedroom</button>
</div>
<script>
filterSelection("all")
function filterSelection(c) {
var x, i;
x = document.getElementsByClassName("filterDiv");
if (c == "all") c = "";
for (i = 0; i < x.length; i++) {
w3RemoveClass(x[i], "show");
if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
}
}
function w3AddClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
if (arr1.indexOf(arr2[i]) == -1) {element.className += " " + arr2[i];}
}
}
function w3RemoveClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
while (arr1.indexOf(arr2[i]) > -1) {
arr1.splice(arr1.indexOf(arr2[i]), 1);
}
}
element.className = arr1.join(" ");
}
// Add active class to the current button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function(){
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
</script>
Joshua Castro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.