I have two HTML files: index and categories. On index.html, I've created the list of categories by using the javascript function and have added tag to direct the user to the categories.html ( all links have the same href attribute). I want to change the content of the categories.html according to the inner text of clicked tag on the previous page.
I used localStorage to store all category names but I don't know how to use those names to fetch accordingly on category.html when I don't know which tag directed the user to the category.html. How can I detect the clicked link?
I'm sharing the element creation & localStorage code in case if the issue can be fixed in that code:
import { fetchData, createListItem} from "../Utils.js";
// List Categories
const createHeroCategories = () => fetchData("https://www.themealdb.com/api/json/v1/1/categories.php")
.then((data) => {
data.categories.forEach((category) =>
createListItem(".categories-list", category["strCategory"], "category-item")
);
Array.from(document.getElementsByClassName('category-item')).forEach(element => {
let temp = element.innerText;
element.innerHTML = `<a href="./pages/categories.html">${temp}</a>`;
localStorage.setItem(`${temp}`, temp);
})
})
.catch((e) => alert(e.message));
export {createHeroCategories};
The issue was solved by adding onclick function that assigns the inner text to a single variable called "clickedItem". It will change the stored value, if another tag is clicked. I come up with this solution as "setItem" method can be used for changing/overwriting the old value of the same variable. The value will be stored when the user is on index.html, just before being directed to the categories.html.
Array.from(document.getElementsByClassName('category-item')).forEach(element => {
let temp = element.innerText;
element.innerHTML = `<a onclick="localStorage.setItem('clickedItem','${temp}');"
href="./pages/categories.html">${temp}</a>`;
})
This way, "clickedItem" can be called on the categories.html, and used to fetch by using template literals like this:
let clickedItem = localStorage.getItem("clickedItem")
let API = `https://www.themealdb.com/api/json/v1/1/filter.php?c=${clickedItem}`
fetch(API).then(...).catch(...)