The event listener fails to function properly in asynchronous JavaScript

The reason for the error is due to the asynchronous nature of the code, where the button is not loaded yet. Is there a solution to this issue? It's difficult to explain in words but essentially, when the window is loaded, the button is not present as it only appears after clicking on an ID. I tried to include all the necessary codes but Stack Overflow requires a more detailed explanation.

Below is my main JavaScript code. The fetch function works correctly and I have omitted some of the codes for brevity.

const controlMovie = async() => {

const id = window.location.hash.replace('#', '');

if(id){
    // new id
    clearMovie();
    state.control = new Control(id);
    await state.control.getMovies();

    UImovie(state.control);
}
return id;
};

const viewList = async() =>
{
    const id = window.location.hash.replace('#', '');
    state.view= new Control(id);
    await state.view.getMovies();
    UIlist(state.view);
}

['hashchange', 'load'].forEach(event => window.addEventListener(event, controlMovie));

document.querySelector('.add').addEventListener('click', viewList);

This part pertains to the UI JavaScript section

const UImovie = (info) => {
    const markup = `
    <div class="img-fig">
    <img src="${info.image}" alt="${info.title}" class="movie-img">
    </div>
    
   <div class="movie_details">
    
           <br>
           <h3 style="align-items: center; font-weight: bold;"> ${info.title}</h3>
        <p>Writer: ${info.writer}</p>
               <p>Released date: ${info.year}</p>
               <p>Actors: ${info.actors} </p>
               <p>imdbRating: ${info.rating}</p>
               <p>Total seasons: ${info.seasons}</p>
               <p style="font-style: italic; color: red; font-size: 16px;"> "${info.story}"</p>
               <button class= "add">+ Add to watchlist</button>
              
           </div>
       </div>
    `;
   document.querySelector('.movies-result').insertAdjacentHTML('afterbegin', markup);
};
const UIlist = (UI) => {
    const markup = `
    <h3> ${UI.title} <button class="icons"><ion-icon name="trash"></ion-icon></button></h3>
    `;
    document.querySelector('.lists').insertAdjacentHTML('afterbegin', markup);
}

Answer №1

Upon review, it appears that in the provided code snippet, the .icons class is being added dynamically. However, the .addEventListener function is being called during page load. As a result, when this function is executed, there are no elements available in the DOM and therefore no listener is added.

To address this issue, consider using HTMLElement objects instead:

const createUIList = (UI)=> {
  const h3 = document.createElement('h3');
  h3.innerText = UI.title;
  
  const button = document.createElement('button');
  const icon = document.createElement('ion-icon');
  icon.setAttribute('name', 'trash');
  button.append(icon);
  button.classList.add('icons');
  
  button.addEventListener('click', function() {
     console.log('Button Clicked');
  })
  
  h3.append(button)
  document.querySelector('.lists').insertAdjacentElement('afterbegin', h3);
}

createUIList( { title: 'Bla' } )
<div>
  <div class='lists'></div>
</div>

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

Customized placement of form fields on an HTML grid determined by the user

My goal is to organize input elements on a grid based on user preferences. After researching, I stumbled upon CSS grids, which seem promising. I am considering creating a CSS grid with r rows and c columns, then using JavaScript to assign input elements t ...

Unable to get CSS transition to function properly after adding a class using jQuery

I am trying to create a hover effect that shows an image when the mouse is over a specific div, but for some reason, the transition is not working as expected. I understand that using visibility: hidden cannot be animated. Here is the code snippet: $(d ...

Strategies for extracting special character codes from API data within a React functional component

I have been experimenting with a simple trivia API to improve my understanding of REACT. I have noticed that the question data is returning with special character codes, which is causing issues with react jsx. Can anyone suggest a method to easily convert ...

Having difficulty with express.index when trying to send a JSON object

Express is my tool of choice for creating a simple web page. The code in my index.js file looks like this: exports.index = function(req, res){ res.render( 'index', { title: 'Expressssss', Tin: va ...

React error: "Unable to locate property 'bind' within the undefined"

After reviewing several solutions, I'm still struggling to understand. Below is my code snippet: // userInputActions.js ... export function dummy() { console.log('dummy function called'); } ... // *userInputPage.js* import * as use ...

Retrieve the file name from the URL while disregarding the query string

Looking for a way to extract the test.jsp from this URL: http://www.xyz.com/a/test.jsp?a=b&c=d Can anyone provide guidance on how to accomplish this task? ...

Using async/await in React to retrieve data after a form submission

I am currently facing an issue with displaying data fetched from an API on the screen. My goal is to retrieve data when a user types something in a form and clicks the submit button. The error message I am encountering is: TypeError: Cannot read propert ...

Getting started with Preact.js: Setting up an auto re-run server similar to React.js

Is there a way to set up a development server for Preact similar to how React operates with npm start? Currently, when I use the same command with Preact, it launches a static server and requires manual restart each time I make changes to my project. Here ...

Introducing a fresh parameter to initiate and end Server Sent Events

Assistance needed. I have implemented Server Sent Events to dynamically update a website using data from a database. Now, I aim to send a new parameter ('abc.php/?lastID=xxx') back to the PHP script based on information received in the previous ...

What method can I use to modify the object's keys based on certain conditions in ES6/React?

How can I dynamically change the value of an object's keys based on specific conditions? What is the most effective way to structure and implement this logic? Data const newData = { id: 111, name: "ewfwef", description: "Hello&qu ...

The event listener for browser.menus.onClicked is dysfunctional in Firefox

Currently, I am in the process of developing my own Firefox extension and I have encountered an issue with adding a listener to an onclick event for a context menu item. manifest.json { "manifest_version": 2, "name": "My exten ...

Tips for retrying an insertion into the database when a duplicate unique value is already present

After thorough searching, I couldn't find any existing patterns. My goal is to store a unique key value in my MySQL database. I generate it on the server side using this code: var pc = require('password-creator'); var key = pc.create(20); ...

A program designed to access and retrieve a universal variable

It seems like a simple task, but I can't seem to figure it out. I'm trying to assign the currentUserId within the getCurrentUser function so that I can use it in other functions. Currently, the code below is returning undefined. What am I overl ...

Tips for avoiding the freezing of bootstrap-select scroll when a large number of options are present

I have integrated a bootstrap-select with a total of 1000 options. However, I am encountering an issue where when I attempt to scroll down the list of options, it only goes down approximately 60 options and then freezes in that position. Can anyone provi ...

Is your Ajax jQuery live search not functioning properly with JSON data?

My programming code is not functioning properly. Here is the file I am working on. When it does work, it does not display the list and gives an error in the Json file. I am unsure of the reason behind this issue. You will be able to view the error in the C ...

Different ways to analyze elements from 2 arrays to hone in on specific values

I'm really struggling to solve this issue. I have two arrays - one for cars and the other for active filters. The cars array consists of HTML li tags with attributes like car type, number of seats, price, etc. On the other hand, the active_filters arr ...

The $routeChangeSuccess event is failing to trigger in ngNewRouter in AngularJS version 1.4

Transitioning from AngularJS 1.3 to AngularJS 1.4 has brought about some changes, including the use of AngularJS's new route method known as ngNewRouter, specifically introduced in AngularJS 1.4. Below is a snippet of my code: var versionModule = ng ...

How can I showcase CSV data as clickable links and images on a website using HTML?

Looking for a way to display CSV file links as clickable hyperlinks in a table? Want to directly show images from photo links on your website as well? Wondering if this is even possible? Successfully showcased desired content in a table with the code prov ...

"Utilizing FileReader to seamlessly integrate data into FormData without the risk

Currently, I'm in the process of constructing an ajax file uploader. This is made possible thanks to the recently introduced FormData interface. Everything seems to work as expected when using the original file. However, I encounter issues when conver ...

EaselJS BitmapAnimation has delay when using gotoAndPlay

I have created a requirejs module that enhances the functionality of a BitmapAnimation by allowing it to move around the stage at a specific speed and transition to another looped animation once reaching its destination. The issue I am encountering is a n ...