Choosing dynamically created components:Making a choice among elements that are generated

Currently, I am working on a task that involves moving list items between two separate lists and then returning them back upon a click event trigger.

Below is a snippet of the basic HTML structure:

Unchosen: <br>
<ul id="unchosen"></ul>

Chosen: <br>
<ul id="chosen"></ul>

<script src="app.js"></script>

And this is the content of app.js:

const unchosenList = document.querySelector('#unchosen');
const chosenList = document.querySelector('#chosen');

let data = [
    {
        id: 1,
        name: 'John Doe'
    },
    {
        id: 2,
        name: 'Jane Doe'
    }
];

data.forEach(e => unchosenList.insertAdjacentHTML('afterbegin', `<li id='person'>${e.name}</li>`));

let person = document.querySelectorAll('#person');

function moveList() {
   person.forEach(e => {
     e.addEventListener('click', function() {
       this.parentNode.removeChild(this);
       chosenList.insertAdjacentHTML('afterbegin', `<li id='chosen-person'>${this.textContent}</li>`);
     });
   });
}

if(person) {
   moveList();
}

let chosenPerson = document.querySelectorAll('#chosen-person');

function returnList() {
   chosenPerson.forEach(e => {
      e.addEventListener('click', function() {
        this.parentNode.removeChild(this);
        unchosenList.insertAdjacentHTML('afterbegin', `<li id='person'>${this.textContent}</li>`);
      });
   });
}

if(chosenPerson) {
   returnList();
}

The issue arises with the returnList function not working as intended due to chosenPerson being undefined. Moreover, there are concerns about how the functionality will impact the existing person array. Any insights or suggestions would be greatly appreciated!

Answer №1

After setting up the event listeners, it became clear that the unchosen-person objects were not yet in existence. As a result, they were created without any associated event listeners.

The solution is to proactively create event listeners for objects that may not exist at the time. One approach is to attach an event listener to the entire document and then dynamically handle events based on the properties of the clicked element:

document.addEventListener('click', function(e) {

    let element = e.target;   

    if (element.id == 'person') {
        unchosenList.removeChild(element);
        chosenList.insertAdjacentHTML(
            'afterbegin', 
            `<li id='chosen-person'>${element.textContent}</li>`
        );
    }   

    else if (element.id == 'chosen-person') {
        chosenList.removeChild(element);
        unchosenList.insertAdjacentHTML(
            'afterbegin', 
            `<li id='person'>${element.textContent}</li>`
        );
    }   

});

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

JavaScript to toggle the visibility of elements when they move outside of a specified container

Check out this js+html/css project I worked on: http://jsfiddle.net/A1ex5andr/xpRrf/ It functions as intended - opening and closing with the use of .advSearch-btn to open/close, and .advSearch-control .canc to close. However, I am facing an issue where it ...

Unlock the potential of AngularJS services with this innovative design strategy

I am currently developing an AngularJS client application that will communicate with a REST server. To handle the interaction between the client and server, I have decided to use the $resource abstraction from AngularJS. Each resource is being written as ...

The instance is referencing "underscore" during render, but it is not defined as a property or method

I have experience as a skilled react developer, but I've taken over a vue.js project from another developer and managed it for quite some time. Regrettably, I haven't put in the effort to learn vue properly. When using lodash, I encountered an u ...

What is the proper way to transfer information to my ajax function from my controller?

I need to dynamically update an element on my webpage based on server-side code events. For example, when I trigger the "Start" function by clicking a button, I want the text inside a specific element to change to "Downloading", and then once the process i ...

How can I utilize the Facebook API on Tizen to share a video?

Could someone please provide guidance on how to incorporate video uploading functionality into a Tizen application using the Facebook API and HTML5? ...

Looking for a dynamic solution to retrieve over 100 data products in Angular JS? Let's explore methods to efficiently call a large volume of

Just starting out with Angular JS and working on creating a searchable product list gallery using Angular JS. Currently, all my product data is in the same js file which I know isn't the best solution. I would like to make it dynamic by connecting to ...

Step-by-step guide on incorporating an external JavaScript library into an Ionic 3 TypeScript project

As part of a project, I am tasked with creating a custom thermostat app. While I initially wanted to use Ionic for this task, I encountered some difficulty in integrating the provided API into my project. The API.js file contains all the necessary function ...

HTML - implementing a login system without the use of PHP

While I am aware that the answer may lean towards being negative, I am currently in the process of developing a series of web pages for an IST assignment in Year 9. Unfortunately, the web page cannot be hosted and our assessor lacks the expertise to utiliz ...

PNG file is not displayed on React TSX page despite absence of any errors

I've implemented this initial design template from GitHub (https://github.com/vikpe/react-webpack-typescript-starter). Additionally, I'm utilizing react-bootstrap and have a container that includes a backgroundImage. const heroImage = require(&q ...

Determining in Express.js whether headers have been sent or not

As I develop a library that involves setting headers, I aim to provide a personalized error message in case the headers have already been sent. Rather than simply letting it fail with the default "Can't set headers after they are sent" message from No ...

Integrate the dForm plugin with a convenient time picker widget

Currently, I am attempting to integrate a time picker widget into a jQuery plugin called dForm. The specific timepicker widget can be found at the following link: https://github.com/jonthornton/jquery-timepicker Despite reviewing the dForm documentation, ...

Ways to retrieve the React Router match object in mapStateToProps

Is there a way to access the react-router match object for its params from mapStateToProps or any other selector? I'd like to use these params to generate a value that will be passed down as props to a presentational component within the selector. The ...

Having difficulty accessing attributes within the template - encountering errors for all attributes except for 'name', stating '[attributename] is not defined'

There seems to be an issue with accessing Object attributes other than 'name' in the template. When trying to access attributes like id or url, errors such as 'id/url/whatever is not defined' are logged in the console. The JSON file pas ...

How to handle non-ASCII characters when encoding in JSON?

I understand that json_encode requires UTF-8 encoding, and I have already ensured that my data is encoded as such. However, when attempting to pass a PHP array to JavaScript, I am encountering difficulties in transferring the data successfully. To test th ...

Click event not functioning correctly in Internet Explorer

When using jQuery, I have the following code: <script type="text/javascript"> $(document).ready(function(){ $('body').on('click', '.add-photo',function() { $("#images").append($('<input/>').attr(&apo ...

Transforming the initial character of a label element into uppercase

When I receive an external HTML page, all the data comes in lowercase. I attempted to capitalize the first letter of each label tag using CSS, but it ended up making the entire text uppercase instead. Here is what I tried: .fontmodal { text-transform ...

Matching list symbols in regular expressions (Angular 2)

I have been attempting to find a solution for matching a list of symbols using regex, but I keep encountering errors in the result. The symbol list includes: !@#$+*{}?<>&’”[]=%^ if (text.match('^[\[\]\!\"\#&bs ...

What could be causing me to receive no results?

Currently, I am expanding my knowledge in JavaScript, Ajax, and NodeJs. My current project involves creating a webpage that can display a string retrieved from the server. The server-side code is as follows: var express = require('express'); v ...

The server is unable to process your request to /graphql

I've encountered an issue while setting up the GraphiQL API. I keep receiving the error message "Cannot POST /graphql" on both the screen and network tab of the console. Despite having similar boilerplate code functioning in another project, I'm ...

Invoking Node to utilize React/Webpack module code

Trying to figure out how to integrate client-side import/export modules into a Node.js require script within my custom NextJS webpack config: module.exports = { webpack: (config, options) => { if (options.isServer) { require("./some-scr ...