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

Unable to successfully add element to array using UIKit modal in vuejs

On my webpage, I have a table that showcases an array of "currency" objects: <tbody> <tr v-for="currency in currencies" v-bind:key="currency.Name"> <td class="uk-width-medium">{{currency.Enabled}}</ ...

Analyzing past UTC date times results in a peculiar shift in time zones

When I receive various times in UTC from a REST application, I encounter different results. Examples include 2999-01-30T23:00:00.000Z and 1699-12-30T23:00:00.000Z. To display these times on the front end, I use new Date(date) in JavaScript to convert the ...

Using the power of node.js to iterate through a loop of queries and execute

While I am running a for loop, within the loop itself I am executing a PostgreSQL query and storing the result in an array. However, I am unable to determine the order of execution. Here is my code: var array =[]; for(var i = 0 ; i< latitude.le ...

How can I configure nest.js to route all requests to index.html in an Angular application?

I am developing an Angular and NestJS application, and my goal is to serve the index.html file for all routes. Main.ts File: async function bootstrap() { const app = await NestFactory.create(AppModule); app.useStaticAssets(join(__dirname, '..&ap ...

Utilizing nodejs to interact with a web service

Recently diving into Node.js and currently exploring how to utilize services with NodeJS. Seeking guidance on the NodeJS equivalent of the code snippet provided below: $.ajax({ type: "POST", url: "/WebServiceUtility.aspx/CustomOrderService", data: " ...

Having trouble sending a POST request from my React frontend to the Node.js backend

My node.js portfolio page features a simple contact form that sends emails using the Sendgrid API. The details for the API request are stored in sendgridObj, which is then sent to my server at server.js via a POST request when the contact form is submitted ...

Only displaying sub items upon clicking the parent item in VueJS

I'm in the process of designing a navigation sidebar with main items and corresponding sub-items. I want the sub-item to be visible only when its parent item is clicked, and when a sub-item is clicked, I aim for it to stand out with a different color. ...

Automate your workflow with Apps Script: Save time by appending a row and seamlessly including additional details to the

I currently have 2 server-side scripts that handle data from an html form. The first script saves user input to the last row available in my Google sheet, while the second script adds additional details to the newly created row. Although both scripts work ...

Web Page Content Scrambling/Character Exchange

I've encountered a perplexing issue that seems to strike randomly, yet I've managed to replicate the problem on three different desktops. Oddly enough, some other desktops never experience this issue and I'm at a loss as to what could be cau ...

Using Json with React's Context API

I am dealing with nested JSON and arrays within it. My goal is to create a Search functionality that will iterate through the arrays and, based on a specific ID, display the name of the corresponding object in the array. I attempted using the Context API ...

Tips for redirecting in the callback of a jQuery post request

After receiving data, my homepage does not redirect to the login page. Below is the JavaScript code for the homepage: $(function(){ const submit = $('#submit'); const save = $('#save'); const email = $('#email'); ...

Can you provide instructions on how to use JavaScript to click and hold a button for a specific duration?

Is it possible to use jQuery to create a button that, when guest button number 1 is clicked, will automatically click and hold down button number 2 for about 3 seconds? I have tried using the mousedown() and click(), but they only register a click, not a ...

Obtain the location of the image source from a text file within an HTML document

I need to create a slideshow displaying a sequence of images. The path to these images will be stored in a text file. How can I read the image paths from the text file? Currently, I have hardcoded code like the example below: <div class="mySlides fade" ...

Having trouble sending JSON data to the server using a POST request

I am encountering an issue while attempting to send JSON data to the server using the fetch API and PHP as the server-side language. The PHP code on the server side is quite simple: <?php header("Access-Control-Allow-Origin: *"); header("Access ...

Having trouble submitting a date input form generated with vuejs on Safari browser

I am a huge fan of Vuejs and it's my go-to at work. The other day, I came across a rather perplexing scenario. If you have any insights into this, please do share. Here is the code in question: <script setup lang="ts"> import { ref ...

A guide to activating an input field based on the value of another input field in AngularJs

An AngularJs form requires the user to input the number of hours worked. If the value entered is 0, an additional question should be displayed for the reason why no work was done. <label>Hours worked:</label> <input ng-model="hours" type="n ...

Combining various postponed JavaScript file imports in the HTML header into a single group

I've been facing an issue with my code structure, particularly with the duplication of header script imports in multiple places. Every time I need to add a new script, I find myself manually inserting <script type="text/javascript" src=&q ...

Rename multiple files in bulk

With 10000 files consisting of php, html, css, and png formats that are interconnected to operate the website's engine, I am looking for a way to perform bulk renaming in order to ensure proper functionality. Not only do I need to rename the actual fi ...

The function correctly identifies the image source without error

I possess a pair of images: <img id="img1" src="l1.jpg" usemap="#lb" height="400" border="0" width="300"> <img src="images.jpg" id="img2"> Next up is some JavaScript: function validateImages () { if (document.getElementById('img2&ap ...

Customize the toggle icon for the accordion in Framework7

I took inspiration from the custom accordion elements provided in the documentation and made some alterations to the icons. However, I'm facing an issue with getting the toggle functionality of the icons to work properly. My goal is to have a "+" dis ...