Enable the event listener for the newly created element

I am attempting to attach an event listener to this HTML element that is being created with an API call

    handleProducts()

    function handleProducts() {

        var display = document.getElementById("display")

        var url = "http://127.0.0.1:8000/api/product/"

        fetch(url)
            .then((resp) => resp.json())
            .then(function (data) {
                console.log(data)

                var products = data

                for (var i in products) {

                    var product = `
                        <div class="col-lg-4">
                            <img class="thumbnail" src="${products[i].img}" alt="">
                                <div class="box-element product">
                                    <h6><strong>${products[i].title}</strong></h6>
                                    <hr>
                                    <button data-product=${products[i].id} data-action = "add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>
                                    <a class="btn btn-outline-success" href="">View</a>
                                    <h4 class="price">${products[i].price}</h4>
                                </div>
                        </div>
                        `
                    display.insertAdjacentHTML('beforeend', product)    
                    
                    
                }
                
            })


            
    }

    function handleAddToCart(){

        var updateBtns = document.getElementsByClassName("update-cart")
        console.log(updateBtns)

        for (var y = 0; y < updateBtns.length; y++) {

            updateBtns[y].addEventListener("click", function () {

                console.log("Clicked")

            })

        }

    }

   handleAddToCart()

I have included the entire code as there may be additional requirements when attaching an event listener to this type of HTML structure. The issue is that clicking the button does not trigger the 'Clicked' message in the console. Any suggestions?

Answer №1

By calling both functions simultaneously, you are attempting to add an event listener before the fetch is finished. To resolve this issue, consider moving the handleAddToCart() function call inside the initial function, immediately after creating the element.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to send emails, SendGrid encounters an error and fails to provide an error code

Earlier today, I successfully sent out a series of emails using SendGrid. It was quite a large number of emails, as I needed to create multiple user accounts with attached email addresses. Thankfully, everything went smoothly and all the emails were delive ...

What are the steps to transform my database object into the Material UI Table structure?

I have a MongoDB data array of objects stored in products. The material design format for creating data rows is as follows: const rows = [ createData('Rice', 305, 3.7, 67, 4.3), createData('Beans', 452, 25.0, 51, 4.9), createData ...

Understanding which page is being rendered through _app.js in React/Next.js is crucial for seamless navigation and

Currently, I am working on rendering my web navigation and footer on my _app.js file. My goal is to dynamically adjust the style of the navigation and footer based on the specific page being accessed. Initially, I considered placing the navigation and foot ...

Ways to organize backbone models, views, and collections using vim?

I am a fan of vim's folding feature, but I have encountered some challenges when trying to fold backbone models, views, and collections. This is because backbone does not follow the traditional prototype syntax, but instead uses a .extend() based synt ...

Error message: App not defined in Ember App.router

Attempting to set up routing for my app for the first time, but struggling to grasp the logic. I managed to render my templates by adding the following code to my route.js file: import Ember from 'ember'; import config from './config/enviro ...

Unexpected JSON token error occurs in jQuery when valid input is provided

I encountered an error that I'm struggling to pinpoint. The issue seems to be related to the presence of the ' symbol in the JSON data. After thoroughly checking, I am positive that the PHP function json_encode is not responsible for adding this ...

Why do I receive the error message "Error: Objects are not valid as a React child (found: [object Promise])" in NextJS13?

I'm feeling overwhelmed by this issue and unsure of how to resolve it. Here is the code that is causing trouble: 'use client' import React, { useState } from 'react' import AnimatedDiv from '../../../(shop)/(components)/animat ...

Verify the existence of the email address, and if it is valid, redirect the user to the dashboard page

Here is the code snippet from my dashboard's page.jsx 'use client' import { useSession } from 'next-auth/react' import { redirect } from 'next/navigation' import { getUserByEmail } from '@/utils/user' export d ...

Issues with Contenteditable functionality in JavaScript

My goal is to make a row editable when a button is clicked. $(":button").click(function(){ var tdvar=$(this).parent('tr').find('td'); $.each(tdvar,function(){ $(this).prop('contenteditable',true); }); }); <s ...

The code is slicing data, but the changes are not reflecting in the user interface

Initially, there are three drop down menus displayed. Upon selecting an option from the first drop down menu, the values in the second drop down menu load. After selecting an option from the second drop down menu, a new set of drop downs appears. However, ...

Performing a request following a POST operation within Postman

Currently, I am using a Post method on a URL which is expected to be written into a database. What I would like to do is create an "if" statement within the test tab in Postman to check the status of the response and then run a query to confirm that the ...

javascript design pattern - achieving unexpected outcome

In the code snippet provided, the variable a is turning out to be undefined. Are you expecting it to display the parameter value passed in the parent function? function test(a) { return function(a) { console.log('a is : ' + a); // Ou ...

Meteor Routing Issue: The path "/"" you are trying to access does not exist in the routing system

After upgrading Meteor to version 1.3.2.4, I encountered an issue where the error message "Error : There is no route for the path: /" appeared. I made sure to update all packages to their latest versions as well. I tested the application in both "meteor" ...

Unable to retrieve Vuex state within a function

Currently, I am developing a Laravel+Vue application where Vuex is used for state management. While working on form validation, everything seems to be progressing smoothly except for one particular issue that has me stuck. The problem arises when I attempt ...

Retrieve the content from a textarea and insert it into a different textarea with additional text included

Users can input HTML codes into a textarea named txtar1. A 'generate' button is available; Upon clicking the 'generate' button, the content of txtar1 will be transfered to another textarea named txtar2 with additional CSS code. Here&ap ...

The basic Node.js API for greeting the world encountered a connection failure

I'm currently working on setting up a basic hello world route using nodejs and express. After running node index.js, I see listening on port 3000 in the console, but when I attempt to access http://localhost:3000/helloworld, it just keeps trying to co ...

The POST method functions properly in the local environment, however, it encounters a 405 (Method Not Allowed) error in the

After testing my code locally and encountering no issues, I uploaded it to Vercel only to run into the error 405 (Method Not Allowed) during the POST method. Despite checking everything thoroughly, I'm unable to find a solution on my own. Your assista ...

AngularJS: intercepting custom 404 errors - handling responses containing URLs

Within my application, I have implemented an interceptor to handle any HTTP response errors. Here is a snippet of how it looks: var response = function(response) { if(response.config.url.indexOf('?page=') > -1) { skipException = true; ...

Contrast between the expressions '$(<%= DDL.ID %>) and $('<%= DDL.ID %>')

I spent hours trying to attach an event to a drop-down list with no success. I even sought help in a JavaScript chat room, but couldn't find a solution. However, by randomly attempting the following code: $('<%= ddl.ID %>').bind(&apos ...

A pair of buttons each displaying a unique div block

I am facing an issue with my jQuery script. I want to be able to click on one of the previewed text associated with a button and then have the other one close automatically. The desired effect is for the text to slide down using slideDown() and disappear ...