Home > front end >  Change content on button click with vanilla js
Change content on button click with vanilla js

Time:07-23

I have an array of objects that is dynamically generated from a JS file. I am mapping buttons from this array for each object. I want to:

  1. Not seeing all objects when loading page but only one, let's say first element by default
  2. Retrieve content according to clicked button and display it, and only this one

I could retrieve clicked button id but couldn't succeed in going further, any help would be welcome.

Here are my files:

index.js


    const menu = [
      {
        id: 1,
        title: "buttermilk pancakes",
        category: "breakfast",
        price: 15.99,
        img: "./images/item-1.jpeg",
        desc: `I'm baby woke mlkshk wolf bitters live-edge blue bottle, hammock freegan copper mug whatever cold-pressed `,
      },
      {
        id: 2,
        title: "diner double",
        category: "lunch",
        price: 13.99,
        img: "./images/item-2.jpeg",
        desc: `vaporware iPhone mumblecore selvage raw denim slow-carb leggings gochujang helvetica man braid jianbing. Marfa thundercats `,
      },
      {
        id: 3,
        title: "godzilla milkshake",
        category: "shakes",
        price: 6.99,
        img: "./images/item-3.jpeg",
        desc: `ombucha chillwave fanny pack 3 wolf moon street art photo booth before they sold out organic viral.`,
      },
      {
        id: 4,
        title: "country delight",
        category: "breakfast",
        price: 20.99,
        img: "./images/item-4.jpeg",
        desc: `Shabby chic keffiyeh neutra snackwave pork belly shoreditch. Prism austin mlkshk truffaut, `,
      },
      {
        id: 5,
        title: "egg attack",
        category: "lunch",
        price: 22.99,
        img: "./images/item-5.jpeg",
        desc: `franzen vegan pabst bicycle rights kickstarter pinterest meditation farm-to-table 90's pop-up `,
      },
      {
        id: 6,
        title: "oreo dream",
        category: "shakes",
        price: 18.99,
        img: "./images/item-6.jpeg",
        desc: `Portland chicharrones ethical edison bulb, palo santo craft beer chia heirloom iPhone everyday`,
      },
      {
        id: 7,
        title: "bacon overflow",
        category: "breakfast",
        price: 8.99,
        img: "./images/item-7.jpeg",
        desc: `carry jianbing normcore freegan. Viral single-origin coffee live-edge, pork belly cloud bread iceland put a bird `,
      },
      {
        id: 8,
        title: "american classic",
        category: "lunch",
        price: 12.99,
        img: "./images/item-8.jpeg",
        desc: `on it tumblr kickstarter thundercats migas everyday carry squid palo santo leggings. Food truck truffaut  `,
      },
      {
        id: 9,
        title: "quarantine buddy",
        category: "shakes",
        price: 16.99,
        img: "./images/item-9.jpeg",
        desc: `skateboard fam synth authentic semiotics. Live-edge lyft af, edison bulb yuccie crucifix microdosing.`,
      },
      {
        id: 10,
        title: "steak dinner",
        category: "dinner",
        price: 39.99,
        img: "./images/item-10.jpeg",
        desc: `skateboard fam synth authentic semiotics. Live-edge lyft af, edison bulb yuccie crucifix microdosing.`,
      },
    ];
    
    const sectionCenter = document.querySelector(".section-center");
    const container = document.querySelector(".btn-container");
    
    // const {id, title, category, price, img, desc} = menu
    
    window.addEventListener("DOMContentLoaded", function () {
      displayMenuItems(menu);
      displayMenuButtons();
    });
    
    function displayMenuItems(menuItems) {
      let displayMenu = menuItems.map(function (item) {
        // console.log(item);
    
        return `<article >
              <img src=${item.img}  alt=${item.title} />
              <div >
                <header>
                  <h4>${item.title}</h4>
                  <h4 >$${item.price}</h4>
                </header>
                <p >
                  ${item.desc}
                </p>
              </div>
            </article>`;
      });
      displayMenu = displayMenu.join("");
    
      sectionCenter.innerHTML = displayMenu;
    }
    
    function displayMenuButtons(){
      const btns = menu.map(function(menuItem){
        // console.log(menuItem)
        return `<button  type="button" data-id=${menuItem.id}>${menuItem.title}</button>`;
      })
      .join("");
      container.innerHTML = btns;
      
      const filterBtns = container.querySelectorAll(".filter-btn");
    
      filterBtns.forEach(function(btn){
        btn.addEventListener("click", function(e){
          const categoryId = e.currentTarget.dataset.id;
          console.log(categoryId)
          const menuCategory = menu.filter(function(menuItem, index){
            // console.log(menuItem)
            console.log(index)
            if(menuItem.id === categoryId){
              return menuItem;
            }
          })
          displayMenuItems(menuCategory)
        })
      })
    
    }

index.html


    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <section >
            <div ></div>
            <div ></div>
        </section>
        <script src="index.js"></script>
    </body>
    </html>```

CodePudding user response:

  1. To only see the first item of the list and without changing the displaymenuitems() function you could do the same as you did for detecting the button press.
window.addEventListener("DOMContentLoaded", function() {
  displayMenuItems(menu.filter(function(menuItem) {
    if (menuItem.id == 1) {
      return menuItem;
    }
  }));
  displayMenuButtons();
});
  1. In order to make the buttons work you need to swap === to == as they are the same value but not the same type. Read more about operators
if(menuItem.id == categoryId){
  return menuItem;
}

I made a JSfiddle https://jsfiddle.net/o7de1b52/1/

CodePudding user response:

Thanks, it works perfectly fine!

  • Related