How to load specific HTML page content when page redirection using JavaScript?

In index.html page of my web site there are three buttons.

Three Buttons in the web site

After clicking these buttons, page redirect to another page named productandservices.html. In their I show fishes for each selected category (when someone select Freshwater fish in index.html, it shows freshwater fishes in productandservices.html).

<a href="servicesAndProduct.html"><button class="menu-buttons">FRESHWATER FISH</button></a>
<a href="servicesAndProduct.html"><button class="menu-buttons">MARINE FISH</button></a>
<a href="servicesAndProduct.html"><button class="menu-buttons">AQUA PLANTS</button></a>

In the exemple, you can see the three buttons in index.html page. But after clicking, they only re-directing page. But do not show the selected category. To achieve that, What I can do in Javascript?

What I want is when someone click on Marine fish index.html, I want to show them Marine fish category in servicesandproduct.html


Solution 1:

Don't really know how your code works in servicesAndProduct.html yet.

For now I assume that your page has static content. So you've all products over there like below. Let's say a div with the content of a product and each div had a few classes for styling, like product, the catecory and a class that hides the product by the default.

<div class="product marine-fish hidden"><!--product content--></div>
<div class="product marine-fish hidden"><!--product content--></div>
<div class="product aqua-plant hidden"><!--product content--></div>

This way you'll be able to select all elements with the class that belongs to the category you want to show and you just remove the hidden class. Then only those elements will be shown.

On your index page change the links as below:

<a href="servicesAndProduct.html?cat=freshwater-fish">
<a href="servicesAndProduct.html?cat=marine-fish">
<a href="servicesAndProduct.html?cat=aqua-plant">

On your servicesAndProduct.html you'll add some Javascript like

const parameters = new URLSearchParams(window.location.search);
const category = parameters.get("cat"); //now this says "freshwater-fish", "marine-fish" or "aqua-plant"


// In this example the only thing you need to do now is show all elements from this category
const elements = document.querySelectorAll("."+category);

elements.forEach(element => {
   element.classList.remove('hidden');
});