skip to Main Content

Maybe i’m just lazy not understanding JQuery that well but i’m a bit in a hurry and think Vanilla JS is just easier for me to grasp creating things with.

I have created a ul consisting of li’s, each consisting with a special product with all the attributes related to it.

I have 2 buttons in the HTML that let’s users navigate through different products (Featured Products) on the page. The buttons trigger the buttonPress() function below.

The products are stored in the Array below.
This code works perfect but needs to be in JQuery syntax.

Thanks in advance.

JS Code:

var products = 
    [
        {
            "id": 1,
            "url": "https://swiftwintekstore.com/products/type-c-usb-3-2-gen2-pcie-card-hub-usb-3-0-pci-express-board-pci-e-pci-e-usb-3-adapter-multiplier-usb3-3-1-controller-riser-cards",
            "rel": "Product page of a Type C USB 3.2 Gen2 PCIE Card Hub USB",
            "title": "Type C USB 3.2 Gen2 PCIE Card Hub",
            "desc": "Type C USB 3.2 Gen2 PCIE Card Hub USB 3.0 Adapter Multiplier USB3 3.1 Controller Riser Cards",
            "discount_amt": 18.2
        },
        { 
            "id": 2,
            "url": "https://swiftwintekstore.com/products/super-si-pro-silicon-fast-charger-mobile-phone-30w",
            "rel": "Product page of a Super Si Pro Silicon Fast Charger Mobile Phone 30W",
            "title": "Super Si Pro Silicon Fast Charger Mobile 30W",
            "desc": "Super Si Pro Silicon Fast Charger Mobile Phone 30W",
            "discount_amt": 7.14
        },
        { 
            "id": 3,
            "url": "https://swiftwintekstore.com/products/zoerax-rj45-pass-through-crimper-for-cat6a-cat6-cat5-cat5e-ethernet-connector-all-in-one-crimp-tool",
            "rel": "Product page of the ZoeRax RJ45 Pass Through Crimper for Cat6a Cat6 Cat5 Cat5e Ethernet Connector",
            "title": "ZoeRax RJ45 Pass Through Crimper for Cat6a Cat6 Cat5 Cat5e Ethernet Connector",
            "desc": "ZoeRax RJ45 Pass Through Crimper for Cat6a Cat6 Cat5 Cat5e Ethernet Connector",
            "discount_amt": 25.0
        },
        { 
            "id": 4,
            "url": "https://swiftwintekstore.com/products/zoerax-network-cable-tester-rj45-rj11-cat5-tool-test-ethernet-telephone-cables?variant=47704487297362",
            "rel": "Product page of the ZoeRax Network Cable Tester RJ45 RJ11 CAT5 Tool",
            "title": "ZoeRax Network Cable Tester RJ45 RJ11 CAT5 Tool",
            "desc": "Ensure your CAT cables are working correctly. Get the ZoeRax Network Cable Tester RJ45 RJ11 CAT5 Tool with this <strong>Huge</strong> discount!",
            "discount_amt": 41.6
        },
        {
            "id": 5,
            "url": "https://swiftwintekstore.com/products/zoerax-all-in-one-pass-through-crimper-for-rj45-rj12-rj11-network-connectors-cat5-5e-6-6a-7?_pos=3&_sid=0cc4887e8&_ss=r",
            "rel": "Product page of the ZoeRax All-in-One Pass Through Crimper for RJ45 RJ12 RJ11 Network Connectors - CAT5/5e/6/6a/7",
            "title": "ZoeRax All-in-One Pass Through Crimper for RJ45 RJ12 RJ11 Network Connectors - CAT5/5e/6/6a/7",
            "desc": "ZoeRax All-in-One Pass Through Crimper for RJ45 RJ12 RJ11 Network Connectors - CAT5/5e/6/6a/7",
            "discount_amt": 19.3
        },
        {
            "id": 6,
            "url": "https://swiftwintekstore.com/products/mini-magnetic-power-bank-10000mah-external-battery",
            "rel": "Product-page-of-a-magnetic-power-bank",
            "title": "mini-magnetic-power-bank-10000mah-external-battery",
            "desc": "New Power Banks in stock, 10000mAh 15WPD",
            "discount_amt": 7.13
        },
        {
            "id": 7,
            "url": "https://swiftwintekstore.com/products/electric-household-small-coffee-automatic-cream-stirrer",
            "rel": "Product-page-of-an-automatic-coffee-cream-stirrer",
            "title": "coffee-automatic-cream-stirrer",
            "desc": "Coffee drinker? Don't miss out on this product",
            "discount_amt": 11.7
        },
        {
            "id": 8,
            "url": "https://swiftwintekstore.com/products/compact-bluetooth-photo-tag-sticker-thermal-printer-for-on-the-go-printing",
            "rel": "Product page of a mobile bluetooth photo printer",
            "title": "compact bluetooth photo sticker printer",
            "desc": "Compact Bluetooth Photo Tag Sticker Thermal Printer for On-the-Go Printing",
            "discount_amt": 15
        },
        {
            "id": 9,
            "url": "https://swiftwintekstore.com/products/zoerax-nvme-pro-adapter-pcie-4-0-ssd-to-desktop-pc-64gbps-m-2-nvme-ssd?variant=47704764809554",
            "rel": "Product page for the ZoeRax NVME Pro Adapter - PCIe 4.0 SSD to Desktop PC - 64Gbps - M.2 NVMe SSD",
            "title": "ZoeRax NVME Pro Adapter - PCIe 4.0 SSD to Desktop PC - 64Gbps - M.2 NVMe SSD",
            "desc": "ZoeRax NVME Pro Adapter - PCIe 4.0 SSD to Desktop PC - 64Gbps - M.2 NVMe SSD",
            "discount_amt": 30
        },
        {
            "id": 10,
            "url": "https://swiftwintekstore.com/products/2-5gbps-pci-e-network-card-stable-wired-connection-for-high-speed-performance-compatible-with-gigabit-ethernet-networks-ce-certified",
            "rel": "Product page of a 2.5Gbps PCI-E Network Card",
            "title": "2.5gbps PCIe network card - CE certified",
            "desc": "2.5Gbps PCI-E Network Card - Stable Wired Connection for High-Speed Performance - Compatible with Gigabit Ethernet Networks - CE Certified",
            "discount_amt": 0
        }
    ];
let add_new_items = true;

// user pressed the left OR Right Chevron button. Replace the 'ul' content
// with new li's consisting of the Object attributes in the Array above.
const buttonPress = () => {
  if (add_new_items) {
    add_products((start_index = 0), (end_index = products.length / 2));
    add_new_items = false;
  } else {
    add_products((start_index = 5), (end_index = products.length));
    add_new_items = true;
  }
};

const add_products = (start_index, end_index) => {
  var products_container = document.getElementById("featured-prod-container");
  products_container.innerHTML = "";
  for (let index = start_index; index < end_index; index++) {
    const product = products[index];
    li = document.createElement("li");
    li.innerHTML = `<li class="product-all" id=${product.id}>
      <a class="in-stock-links" href="${product.url}"
          rel="${product.rel}" title="${product.title}">
          <p class="product-desc">
              ${product.desc}
          </p>
          <p class="discount-amount">
              <span class="now">Now ${product.discount_amt}% Off </span>
          </p>
      </a>
      </li>`;
    products_container.appendChild(li);
  }
};

I have tried converting to Jquery syntax but doesn’t get it to work.

2

Answers


  1. I see that you are coming from a python background, given the variables use snake_case. In JavaScript, variables are typically camaleCase. Also, JavaScript does not use **kwargs. If you call a function, you need to supply the params in the order specified. Although you can technically destructure an incoming object as if it were a dictionary.

    Now for the jQuery part, you can just pass the entire template literal string to the $() call to construct the <li> element.

    The demo below is not a complete solution. I did not implement paging for you, because you can find out how to do that all over the web. Both buttons are calling the same function. Your prev and next buttons should behave differently. The Prev should page backwards and Next should page forwards.

    const allProducts = getAllProducts();
    let addNewItems = true;
    
    $('.btn').on('click', buttonPress);
    
    // User pressed the left OR Right Chevron button.
    // Replace the 'ul' content with new <li> elements
    // consisting of the Object attributes in the Array above.
    function buttonPress(e) {
      const halfIndex = Math.floor(allProducts.length / 2);
      if (addNewItems) {
        displayProducts(0, halfIndex);
        addNewItems = false;
      } else {
        displayProducts(halfIndex, allProducts.length);
        addNewItems = true;
      }
    }
    
    function displayProducts(startIndex, endIndex) {
      const $container = $('#featured-prod-container').empty();
      for (let index = startIndex; index < endIndex; index++) {
        const product = allProducts[index];
        const { id, url, title, rel, desc, discount_amt } = product;
        $container.append(`
          <li class="product-all" id=${id}>
            <a class="in-stock-links" href="${url}"
                rel="${rel}" title="${title}">
                <p class="product-desc">
                    ${desc}
                </p>
                <p class="discount-amount">
                    <span class="now">Now ${discount_amt}% Off </span>
                </p>
            </a>
          </li>
        `);
      }
    }
    
    function getAllProducts() {
      return [{
          "id": 1,
          "url": "https://swiftwintekstore.com/products/type-c-usb-3-2-gen2-pcie-card-hub-usb-3-0-pci-express-board-pci-e-pci-e-usb-3-adapter-multiplier-usb3-3-1-controller-riser-cards",
          "rel": "Product page of a Type C USB 3.2 Gen2 PCIE Card Hub USB",
          "title": "Type C USB 3.2 Gen2 PCIE Card Hub",
          "desc": "Type C USB 3.2 Gen2 PCIE Card Hub USB 3.0 Adapter Multiplier USB3 3.1 Controller Riser Cards",
          "discount_amt": 18.2
        },
        {
          "id": 2,
          "url": "https://swiftwintekstore.com/products/super-si-pro-silicon-fast-charger-mobile-phone-30w",
          "rel": "Product page of a Super Si Pro Silicon Fast Charger Mobile Phone 30W",
          "title": "Super Si Pro Silicon Fast Charger Mobile 30W",
          "desc": "Super Si Pro Silicon Fast Charger Mobile Phone 30W",
          "discount_amt": 7.14
        },
        {
          "id": 3,
          "url": "https://swiftwintekstore.com/products/zoerax-rj45-pass-through-crimper-for-cat6a-cat6-cat5-cat5e-ethernet-connector-all-in-one-crimp-tool",
          "rel": "Product page of the ZoeRax RJ45 Pass Through Crimper for Cat6a Cat6 Cat5 Cat5e Ethernet Connector",
          "title": "ZoeRax RJ45 Pass Through Crimper for Cat6a Cat6 Cat5 Cat5e Ethernet Connector",
          "desc": "ZoeRax RJ45 Pass Through Crimper for Cat6a Cat6 Cat5 Cat5e Ethernet Connector",
          "discount_amt": 25.0
        },
        {
          "id": 4,
          "url": "https://swiftwintekstore.com/products/zoerax-network-cable-tester-rj45-rj11-cat5-tool-test-ethernet-telephone-cables?variant=47704487297362",
          "rel": "Product page of the ZoeRax Network Cable Tester RJ45 RJ11 CAT5 Tool",
          "title": "ZoeRax Network Cable Tester RJ45 RJ11 CAT5 Tool",
          "desc": "Ensure your CAT cables are working correctly. Get the ZoeRax Network Cable Tester RJ45 RJ11 CAT5 Tool with this <strong>Huge</strong> discount!",
          "discount_amt": 41.6
        },
        {
          "id": 5,
          "url": "https://swiftwintekstore.com/products/zoerax-all-in-one-pass-through-crimper-for-rj45-rj12-rj11-network-connectors-cat5-5e-6-6a-7?_pos=3&_sid=0cc4887e8&_ss=r",
          "rel": "Product page of the ZoeRax All-in-One Pass Through Crimper for RJ45 RJ12 RJ11 Network Connectors - CAT5/5e/6/6a/7",
          "title": "ZoeRax All-in-One Pass Through Crimper for RJ45 RJ12 RJ11 Network Connectors - CAT5/5e/6/6a/7",
          "desc": "ZoeRax All-in-One Pass Through Crimper for RJ45 RJ12 RJ11 Network Connectors - CAT5/5e/6/6a/7",
          "discount_amt": 19.3
        },
        {
          "id": 6,
          "url": "https://swiftwintekstore.com/products/mini-magnetic-power-bank-10000mah-external-battery",
          "rel": "Product-page-of-a-magnetic-power-bank",
          "title": "mini-magnetic-power-bank-10000mah-external-battery",
          "desc": "New Power Banks in stock, 10000mAh 15WPD",
          "discount_amt": 7.13
        },
        {
          "id": 7,
          "url": "https://swiftwintekstore.com/products/electric-household-small-coffee-automatic-cream-stirrer",
          "rel": "Product-page-of-an-automatic-coffee-cream-stirrer",
          "title": "coffee-automatic-cream-stirrer",
          "desc": "Coffee drinker? Don't miss out on this product",
          "discount_amt": 11.7
        },
        {
          "id": 8,
          "url": "https://swiftwintekstore.com/products/compact-bluetooth-photo-tag-sticker-thermal-printer-for-on-the-go-printing",
          "rel": "Product page of a mobile bluetooth photo printer",
          "title": "compact bluetooth photo sticker printer",
          "desc": "Compact Bluetooth Photo Tag Sticker Thermal Printer for On-the-Go Printing",
          "discount_amt": 15
        },
        {
          "id": 9,
          "url": "https://swiftwintekstore.com/products/zoerax-nvme-pro-adapter-pcie-4-0-ssd-to-desktop-pc-64gbps-m-2-nvme-ssd?variant=47704764809554",
          "rel": "Product page for the ZoeRax NVME Pro Adapter - PCIe 4.0 SSD to Desktop PC - 64Gbps - M.2 NVMe SSD",
          "title": "ZoeRax NVME Pro Adapter - PCIe 4.0 SSD to Desktop PC - 64Gbps - M.2 NVMe SSD",
          "desc": "ZoeRax NVME Pro Adapter - PCIe 4.0 SSD to Desktop PC - 64Gbps - M.2 NVMe SSD",
          "discount_amt": 30
        },
        {
          "id": 10,
          "url": "https://swiftwintekstore.com/products/2-5gbps-pci-e-network-card-stable-wired-connection-for-high-speed-performance-compatible-with-gigabit-ethernet-networks-ce-certified",
          "rel": "Product page of a 2.5Gbps PCI-E Network Card",
          "title": "2.5gbps PCIe network card - CE certified",
          "desc": "2.5Gbps PCI-E Network Card - Stable Wired Connection for High-Speed Performance - Compatible with Gigabit Ethernet Networks - CE Certified",
          "discount_amt": 0
        }
      ];
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <button type="button" class="btn btn-prev">Prev</button>
    <button type="button" class="btn btn-next">Next</button>
    <hr />
    <ul id="featured-prod-container"></ul>
    Login or Signup to reply.
  2. You certainly don’t need jQuery for this.

    The only real problem I see is that you’re nesting an <li> directly within an <li> which isn’t a valid DOM structure.

    Assuming products_container is a <ul> or <ol>, you might find this works better…

    products_container.innerHTML = '';
    products_container.append(
      ...products
        .slice(start_index, end_index)
        .map(({ id, url, rel, title, desc, discount_amt }) => {
          const li = document.createElement('li');
          li.className = 'product-all';
          li.id = id;
    
          const a = document.createElement('a');
          a.className = 'in-stock-links';
          a.href = url;
          a.rel = rel;
          a.title = title;
    
          const p_desc = document.createElement('p');
          p_desc.className = 'product-desc';
          p_desc.textContent = desc;
    
          const p_discount = document.createElement('p');
          p_discount.className = 'discount-amount';
    
          const span = document.createElement('span');
          span.className = 'now';
          span.textContent = `Now ${discount_amt}% Off `;
    
          p_discount.append(span);
          a.append(p_desc, p_discount);
          li.append(a);
          return li;
        }),
    );
    

    I’m not a fan of using innerHTML since it’s prone to issues with quotes and potential XSS.

    An alternative is to use an HTML <template> which cuts down on some of the boilerplate element creation

    const products = [{"id":1,"url":"https://swiftwintekstore.com/products/type-c-usb-3-2-gen2-pcie-card-hub-usb-3-0-pci-express-board-pci-e-pci-e-usb-3-adapter-multiplier-usb3-3-1-controller-riser-cards","rel":"Product page of a Type C USB 3.2 Gen2 PCIE Card Hub USB","title":"Type C USB 3.2 Gen2 PCIE Card Hub","desc":"Type C USB 3.2 Gen2 PCIE Card Hub USB 3.0 Adapter Multiplier USB3 3.1 Controller Riser Cards","discount_amt":18.2},{"id":2,"url":"https://swiftwintekstore.com/products/super-si-pro-silicon-fast-charger-mobile-phone-30w","rel":"Product page of a Super Si Pro Silicon Fast Charger Mobile Phone 30W","title":"Super Si Pro Silicon Fast Charger Mobile 30W","desc":"Super Si Pro Silicon Fast Charger Mobile Phone 30W","discount_amt":7.14},{"id":3,"url":"https://swiftwintekstore.com/products/zoerax-rj45-pass-through-crimper-for-cat6a-cat6-cat5-cat5e-ethernet-connector-all-in-one-crimp-tool","rel":"Product page of the ZoeRax RJ45 Pass Through Crimper for Cat6a Cat6 Cat5 Cat5e Ethernet Connector","title":"ZoeRax RJ45 Pass Through Crimper for Cat6a Cat6 Cat5 Cat5e Ethernet Connector","desc":"ZoeRax RJ45 Pass Through Crimper for Cat6a Cat6 Cat5 Cat5e Ethernet Connector","discount_amt":25},{"id":4,"url":"https://swiftwintekstore.com/products/zoerax-network-cable-tester-rj45-rj11-cat5-tool-test-ethernet-telephone-cables?variant=47704487297362","rel":"Product page of the ZoeRax Network Cable Tester RJ45 RJ11 CAT5 Tool","title":"ZoeRax Network Cable Tester RJ45 RJ11 CAT5 Tool","desc":"Ensure your CAT cables are working correctly. Get the ZoeRax Network Cable Tester RJ45 RJ11 CAT5 Tool with this <strong>Huge</strong> discount!","discount_amt":41.6},{"id":5,"url":"https://swiftwintekstore.com/products/zoerax-all-in-one-pass-through-crimper-for-rj45-rj12-rj11-network-connectors-cat5-5e-6-6a-7?_pos=3&_sid=0cc4887e8&_ss=r","rel":"Product page of the ZoeRax All-in-One Pass Through Crimper for RJ45 RJ12 RJ11 Network Connectors - CAT5/5e/6/6a/7","title":"ZoeRax All-in-One Pass Through Crimper for RJ45 RJ12 RJ11 Network Connectors - CAT5/5e/6/6a/7","desc":"ZoeRax All-in-One Pass Through Crimper for RJ45 RJ12 RJ11 Network Connectors - CAT5/5e/6/6a/7","discount_amt":19.3},{"id":6,"url":"https://swiftwintekstore.com/products/mini-magnetic-power-bank-10000mah-external-battery","rel":"Product-page-of-a-magnetic-power-bank","title":"mini-magnetic-power-bank-10000mah-external-battery","desc":"New Power Banks in stock, 10000mAh 15WPD","discount_amt":7.13},{"id":7,"url":"https://swiftwintekstore.com/products/electric-household-small-coffee-automatic-cream-stirrer","rel":"Product-page-of-an-automatic-coffee-cream-stirrer","title":"coffee-automatic-cream-stirrer","desc":"Coffee drinker? Don't miss out on this product","discount_amt":11.7},{"id":8,"url":"https://swiftwintekstore.com/products/compact-bluetooth-photo-tag-sticker-thermal-printer-for-on-the-go-printing","rel":"Product page of a mobile bluetooth photo printer","title":"compact bluetooth photo sticker printer","desc":"Compact Bluetooth Photo Tag Sticker Thermal Printer for On-the-Go Printing","discount_amt":15},{"id":9,"url":"https://swiftwintekstore.com/products/zoerax-nvme-pro-adapter-pcie-4-0-ssd-to-desktop-pc-64gbps-m-2-nvme-ssd?variant=47704764809554","rel":"Product page for the ZoeRax NVME Pro Adapter - PCIe 4.0 SSD to Desktop PC - 64Gbps - M.2 NVMe SSD","title":"ZoeRax NVME Pro Adapter - PCIe 4.0 SSD to Desktop PC - 64Gbps - M.2 NVMe SSD","desc":"ZoeRax NVME Pro Adapter - PCIe 4.0 SSD to Desktop PC - 64Gbps - M.2 NVMe SSD","discount_amt":30},{"id":10,"url":"https://swiftwintekstore.com/products/2-5gbps-pci-e-network-card-stable-wired-connection-for-high-speed-performance-compatible-with-gigabit-ethernet-networks-ce-certified","rel":"Product page of a 2.5Gbps PCI-E Network Card","title":"2.5gbps PCIe network card - CE certified","desc":"2.5Gbps PCI-E Network Card - Stable Wired Connection for High-Speed Performance - Compatible with Gigabit Ethernet Networks - CE Certified","discount_amt":0}];
    
    const products_container = document.getElementById('featured-prod-container');
    const template = document.getElementById('product-tpl');
    let add_new_items = true;
    
    const add_products = (start_index, end_index) => {
      products_container.innerHTML = '';
      products_container.append(
        ...products
          .slice(start_index, end_index)
          .map(({ id, url, rel, title, desc, discount_amt }) => {
            const node = template.content.cloneNode(true);
            Object.assign(node.querySelector('li'), { id });
            Object.assign(node.querySelector('a'), { href: url, rel, title });
            node.querySelector('.product-desc').textContent = desc;
            node.querySelector('.now').textContent = `Now ${discount_amt}% Off `;
            return node;
          }),
      );
    };
    
    document.querySelector('button').addEventListener('click', () => {
      if (add_new_items) {
        add_products(0, Math.ceil(products.length / 2));
        add_new_items = false;
      } else {
        add_products(5, products.length);
        add_new_items = true;
      }
    });
    <template id="product-tpl">
      <li class="product-all">
        <a class="in-stock-links">
          <p class="product-desc"></p>
          <p class="discount-amount">
            <span class="now"></span>
          </p>
        </a>
      </li>
    </template>
    
    <button type="button">Add Products</button>
    
    <ul id="featured-prod-container"></ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search