Codementor Events

How to hide or show data from array on click in WordPress using Vanilla JavaScript

Published May 17, 2021

By avoaja in Click Events, HTML, JavaScript, Map, PHP, WordPress, WordPress Custom Themes
May 2020

Introduction

When working on a website, do you need a way to quickly display static data based on user interaction, like clicking on a button? In this tutorial, we would look at how to display data based on what the user clicked, like the image below.

In this example, we would use a list of stores. The stores have three categories, physical stores, delivery stores, restaurants (restaurant locations).

Hide / show items on click

WordPress Settings

Read this section if you are using WordPress

Type this code into your functions.php file, please note that the “location.js” file is located in the “js” folder, which is in the “assets” folder, and the “assets” folder is in the root of your theme folder.

location.js file location

function real_estate_theme_files() {
  wp_enqueue_script( 'location.js', get_theme_file_uri('/assets/js/location.js'), NULL, '2.0', true );
}

If you are not using WordPress, you can go ahead and include the JavaScript file in the HTML.

The HTML

Below is the HTML code for the page.

<div class="container-fluid">
    <div class="row">
        <div class="col-md-6 store-location-select" 
            style="border-right: 1px solid #e9e9e9">
            <div class="sidebar-item pt-5 pl-5">
                <div class="make-me-sticky pl-5">
                    <p class="text-muted"><small>Filters</small></p>
                    <form name="location_display_form">
                        <input 
                            type="radio" 
                            class="input-radio text-muted store_type" 
                            id="all" name="store_type"
                            value="all" checked>
                        <label class="pl-3" for="all">All</label><br>
                        <input 
                            type="radio" 
                            class="input-radio text-muted store_type" 
                            id="store" name="store_type"
                            value="store">
                        <label class="pl-3" for="store">Stores</label><br>
                        <input 
                            type="radio" 
                            class="input-radio text-muted store_type" 
                            id="delivery" name="store_type"
                            value="delivery">
                        <label class="pl-3" for="delivery">Delivery</label><br>
                        <input 
                            type="radio" 
                            class="input-radio text-muted store_type" 
                            id="restaurants" name="store_type"
                            value="restaurants">
                        <label class="pl-3" for="restaurants">Restaurants</label>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="content-section">
                <div id="location-number"></div>
                <div id="location-list">
                </div>
            </div>
        </div>
    </div>
</div>

This HTML comprises of the form that holds the different store types that can be clicked, this can be found on the left side of the image above. It also holds the HTML elements that the JavaScript will populate, “location-number” – for the number of items found, and “location-list” – to display the items themselves.

The JavaScript Section

The array

data = [
    {
        "name": "Farmest Inc",
        "address": "7060 Philmont Court Bedford Hills",
        "city": "NY 10507",
        "location_type": "store"
    },
    {
        "name": "Cradle Farm",
        "address": "64 Gainsway Court Cold Spring",
        "city": "NY 10516",
        "location_type": "store"
    },
    {
        "name": "Thrive Farm & Gardens",
        "address": "751 Heirloom St. Durhamville Rue laBoéti e",
        "city": "NY 13054",
        "location_type": "store"
    },
    {
        "name": "Culture Products",
        "address": "541 Kingwood Drive Rotterdam Junction",
        "city": "NY 12150",
        "location_type": "store"
    },
    {
        "name": "Greengill Farms",
        "address": "7411 Market Road West Kill",
        "city": "NY 12492",
        "location_type": "store"
    },
    {
        "name": "Johnson Botta Farms",
        "address": "8026 Whitemarsh Ave. Brooklyn",
        "city": "NY 11208",
        "location_type": "store"
    },
    {
        "name": "Verrifa Farms",
        "address": "205 Brickell Court Swan Lake",
        "city": "NY 12783",
        "location_type": "store"
    },
    {
        "name": "Garden Fresh",
        "address": "9283 Smoky Hollow St. New York",
        "city": "NY 10282",
        "location_type": "store"
    },
    {
        "name": "Clean Brothers Farms",
        "address": "487 Nut Swamp Ave. Staten Island",
        "city": "NY 10314",
        "location_type": "delivery"
    },
    {
        "name": "Farm With Us",
        "address": "37 Pin Oak St. Astoria",
        "city": "NY 11105",
        "location_type": "delivery"
    }
]

The array contains objects, their keys (name, address, city, location_type) and their respective values.

The JavaScript Code

if (document.forms["location_display_form"].elements["store_type"] !== undefined) {
    var selected_location = "";
    window.onload = function () {
        show_location("all");
    }
    
    var radios = document.forms["location_display_form"].elements["store_type"];
    
    for(var i = 0, max = radios.length; i < max; i++) {
        radios[i].onclick = function() {
            show_location(this.value);
        }
    }
    
    function show_location(selected_location = null) {
        var filtered_data = data;
    
        if (selected_location !== "all") {
            filtered_data = data.filter((obj, index, arr) => {
                return obj.location_type == selected_location
            });
        }
    
        document.getElementById("location-list").innerHTML = "";
        document.getElementById("location-number").innerHTML = '';
    
        for (let index = 0; index < filtered_data.length; index++) {
    
            var name = filtered_data[index].name;
            var address = filtered_data[index].address;
            var city = filtered_data[index].city;
            var location_type = filtered_data[index].location_type;
    
            var badge = document.createElement('div');
            badge.className = 'text-left pl-3';
            badge.innerHTML = '<div class="font-weight-bold block">' + name + '</div>' +
                '<div class="block">' + address + '</div>' +
                '<p>' + city + '</p>';
    
            document.getElementById("location-list").appendChild(badge);
        }
    
        var result_number;
        if (filtered_data.length > 0) {
            result_number = filtered_data.length + " locations";
        } else {
            result_number = "No " + selected_location;
        }
        document.getElementById("location-number").innerHTML = '<p class="pl-5"><small>' + result_number + '</small></p>';
    
        filtered_data = [];
    }
}

The JavaScript Explanation

We start the JavaScript code with an if statement, to check if the element is found on the current page. If this is true, it means the elements are on the current page then the rest of the code will execute, else the rest of the code will be skipped. This check prevents errors on pages that we are not interested in.

Then we initialize a variable “selected_location” that will be used to hold the value of the clicked radio buttons.

The windows.onload, will run the function “show_location” that displays the locations, and pass it the value of “all” so that all the locations will be visible when the page loads.

var radios = document.forms["location_display_form"].elements["store_type"];
    
    for(var i = 0, max = radios.length; i < max; i++) {
        radios[i].onclick = function() {
            show_location(this.value);
        }
    }

Next, we pick all the elements “store_type” – the “name” of each radio button that are in the “location_display_form” – the name of the form the radio buttons are found in.

Next, we loop through var - radios, to find the particular button that has been clicked, then call the show_location(), and pass the value of that radio button to the function.

var filtered_data = data;
    
if (selected_location !== "all") {
   filtered_data = data.filter((obj, index, arr) => {
       return obj.location_type == selected_location
   });
}

In the next code, which is same as the one above, we map a new variable “filtered_data” to data. Instead of editing the original array directly, in case, the user clicks on something else. We can repopulate the location and then go ahead to filter.

for (let index = 0; index < filtered_data.length; index++) {
    
    var name = filtered_data[index].name;
    var address = filtered_data[index].address;
    var city = filtered_data[index].city;
    var location_type = filtered_data[index].location_type;

    var badge = document.createElement('div');
    badge.className = 'text-left pl-3';
    badge.innerHTML = '<div class="font-weight-bold block">' + name + '</div>' +
        '<div class="block">' + address + '</div>' +
        '<p>' + city + '</p>';

    document.getElementById("location-list").appendChild(badge);
}

In the if statement, we check if the selected_location, is all. If it is all we skip the function, so that the new array filtered_data, is not sorted. If the selected_location is not all, then we filter for only the ones that have location_type as the selected_location.

The next for statement loops through the filtered_data to produce the required HTML, and append it to the div element with id of location-list so that it is now visible on the front-end.

var result_number;
if (filtered_data.length > 0) {
    result_number = filtered_data.length + " locations";
} else {
    result_number = "No " + selected_location;
}
document.getElementById("location-number").innerHTML = '<p class="pl-5"><small>' + result_number + '</small></p>';

This portion of the code above will count the number of records to produce the number of locations related to the selected item. For example, it is responsible for displaying “10 Locations” when all is selected or “No restaurants”, if no result is found.

filtered_data = [];

The final part of the code, just empties the filtered_data array, so that when the store type is clicked again, the new results will not be appended to the old ones.

Discover and read more posts from Charles Avoaja
get started
post commentsBe the first to share your opinion
Show more replies