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

Breaking circular dependencies in JavaScript is a common challenge that developers face when

Having encountered a circular dependency issue between certain JS files, I am seeking steps to resolve it. Q1: Is repositioning the require function an appropriate solution? One suggested approach to resolve this issue is to move the require() statement ...

Can a ng-repeat value be assigned to a text input field?

<tr ng-repeat="person in users" ng-class="{'chosen': person.AdmissionID == currentSelection}" ng-click="selectRow(person.AdmissionID)"> <td>{{person.AdmissionID}}</td> <td>{{person.AdmissionNumber}}</td> ...

The HTML button fails to respond when clicked

My website development process has hit a snag with the header buttons not functioning properly. I suspect the issues lie within lines 12 to 15 of the code snippet below: <!DOCTYPE html> <html> <head> <script src="https: ...

A guide to setting a custom icon for the DatePicker component in Material-UI 5

Seeking to incorporate custom Icons from react-feathers, I have implemented a CustomIcon component which returns the desired icon based on the name prop. Below is the code for this component. import React from 'react'; import * as Icon from &apo ...

The success callback method is no longer correctly referencing the variable due to a change in the AJAX request

Imagine you have a table in your HTML file with the following rows, where {{ }} represent variables: <tr id="{{ object.id }}"> <td class="name">{{ object.name }}</td> </tr> <tr id="{{ object.id }}"> <td class="nam ...

The image begins rotating only after the second click has been made

Having trouble with jQuery and rotation effects on an image? I have a solution for you. The image should rotate while toggling at the same time, but there's a twist - on the first click, it won't rotate but will still toggle. From the second clic ...

Transforming data from a JSON format into a JavaScript array

I'm trying to convert a JSON string into an array containing the values from the JSON. When I use json.stringify(jsonmybe) and alert it, I see [{"role":"noi_user"},{"role":"bert_user"}] (which is in JSON format). My goal is to extract `noi_user` and ` ...

Pass data from Action Class to ajax using JSON syntax

Currently I am facing an issue while working on fullCalendar, a jQuery plugin. I am trying to populate event details from a database when the Calendar page loads, but I seem to be stuck with a silly problem that I can't figure out. $('#calendar& ...

Struggling to determine the expense upon button activation - data remains stagnant

My coding project involves a basic ordering system where users can input an integer, click on an update button, and see the total cost displayed below. Despite my efforts, I've encountered issues with two different methods: Using plain JavaScript for ...

Exploring the differences between two CSS style attributes using JQuery

Can someone help me with a quick question about CSS? I need to compare two style attributes, specifically margin-left. If the margin-left is less than 500px, I don't want to make any changes. However, if it's greater than 500px, I want to add ano ...

Filter information by the K column within Google Script Editor on Google Sheets

For this particular case, I have data coming from a Google Sheet (4Cat) that is being transferred to another sheet (ImportFeeder) where my Google Script is executed. After executing the script provided below, I am looking to implement a filter script at t ...

Yep, implementing conditional logic with the `when` keyword and radio buttons

I seem to be encountering an issue with my implementation (probably something trivial). I am utilizing React Hook Form along with Yup and attempting to establish a condition based on the selection of a radio group. The scenario is as follows: if the first ...

What is the correct way to utilize JSON with AJAX?

I am looking to transfer data from a php backend to a browser using JSON. I have a basic understanding of the process and have included an example code snippet below. However, I have been advised that this may not be the most efficient approach. Due to my ...

Crafting a Visual Storybook with Express.js

I am currently working on developing a photo album app using MEVN. In this project, the value of req.body.ALBUM is used as the folder name and req.body.DESCRIPTION is designated for describing the content. The issue I have encountered so far is that whil ...

Steps to create folders in dat.gui:

I'm attempting to incorporate folders for the lights in a three.js project that I borrowed from a three.js example. However, I am struggling to make it work. From what I gather, I should use f1=add.folder('light1') and then somehow add the p ...

Passport JS receiving negative request

I'm currently experiencing an issue with the passport req.login function. When a user logs in using their email and password, instead of redirecting to /productos2 as intended, it routes to a bad request page. I am utilizing ejs and mongoose for this ...

Utilizing Browser and Operating System Information as Body Class

In order to achieve pixel-perfect styling, I want to include the OS and browser information in the body class. This is necessary because fonts may appear differently depending on the OS/browser configuration. After some research and experimentation, I came ...

After refreshing the page, the JQuery radio button will still be selected

In my form, a radio button triggers an additional text field based on user selection. To achieve this functionality, I am using the following jQuery script: $(document).ready(function(){ $('input:radio[name="accountType"]').change(function() ...

Loading WordPress posts using Ajax

Struggling with getting an Ajax post loader to work properly. Following the jQuery code from a previous StackOverflow post titled "Load More Posts" with Ajax in WordPress, but still facing issues. Trying to implement an isotope list for ajax loading more p ...

Is it possible to create a form inside a tooltip?

Looking to incorporate a jQuery feature into a form where a simple yes or no question appears upon hovering over it. However, encountering issues getting jQuery to recognize the dynamically created tooltip and submit alert function not working ("$('#w ...