The challenge of removing an event listener

There are three Div elements with a box appearance. When the user clicks on any div, a copy of that div will be added to the end. The original clicked div will no longer be clickable, but the new div will be. This process can repeat indefinitely.

I attempted this, but it ended up creating two divs simultaneously and the div became clickable again!


<div id="parent" class="p">
    <div class="red" class="d"></div>
    <div class="green" class="d"></div>
    <div class="blue" class="d"></div>
</div>
#parent{
display: flex;
flex-wrap: wrap;
 }

.red{
   
    width: 50px;
    height: 50px;
    background-color: red;
    margin: 2px;
}
.green{
    
    width: 50px;
    height: 50px;
    background-color: green;
    margin: 2px;
}
.blue{
   
    width: 50px;
    height: 50px;
    background-color: blue;
    margin: 2px;
}
let parent = document.querySelector("#parent");
let div = document.querySelectorAll(".p div");

parent.addEventListener("click", function createDiv(e){ 
console.log('1');
let child = document.createElement("div");
parent.append(child);
child.classList.add(e.target.className);
console.log(e);
e.target.removeEventListener("click",createDiv());
});

Answer №1

this way...

An eventListener serves as a bridge between a DOM element and a function.

To delete any event listener, you must match the same pair [ DOM element / function ].

In this scenario, the connection is on the parent element rather than on any of its child divs. Hence, it is not possible to remove the link between the original divs.

const
  parent = document.querySelector('#parent')
, cDivs  = document.querySelectorAll('#parent > div')
  ;
cDivs.forEach(div => div.addEventListener('click', createDiv)) // ensure that `createDiv` function is only created once
  ;
function createDiv({currentTarget: initialDiv}) // declare the function just once
  {
  initialDiv.removeEventListener('click', createDiv)
    ;
  parent
    .appendChild( initialDiv.cloneNode(true) )  // cloning the element
    .addEventListener('click', createDiv)
  }
#parent {
  display   : flex;
  flex-wrap : wrap;
  }
#parent > div {
  width  : 50px;
  height : 50px;
  margin : 2px;
  }
.red {
  background : red;
  }
.green {
  background : green;
  }
.blue {
  background : blue;
  }
<div id="parent" class="p">
  <div class="red"   ></div>
  <div class="green" ></div>
  <div class="blue"  ></div>
</div>

Answer №2

const container = document.getElementById("container");

// handling all clicks on the container with one function
container.addEventListener("click", function(e) {
  // retrieve the element that was clicked on
  const el = e.target;
  // ensuring the click is on an inner div and hasn't been clicked before
  if (el !== this && !el.dataset.clicked) {
    // create a clone of the clicked element
    const clone = el.cloneNode(true);
    // append the cloned element to the end of the container
    this.appendChild(clone);
    // mark the original element as clicked
    el.dataset.clicked = true;
  }
});
#container {
  display: flex;
  flex-wrap: wrap;
}

#container > div {
  width: 50px;
  height: 50px;
  margin: 2px;
}

.red {
  background: red;
}

.green {
  background: green;
}

.blue {
  background: blue;
}
<div id="container" class="c">
  <div class="red"></div>
  <div class="green"></div>
  <div class="blue"></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

implementing a fixed header in HTML

I am facing a challenge where I have a header with dynamic height and fixed position. My goal is to position the container div right below the header. However, since the header height varies, using a fixed value for margin-top is not feasible. Any sugges ...

Utilize JavaScript to extract an image from an external URL by specifying its attributes (id, class)

Is it possible to fetch an image from an external website by using its CSS id or class in conjunction with JavaScript/jQuery's get methods? If so, could someone provide guidance on how to achieve this task? ...

A program that saves numerous data from a JSON dictionary into an array

I have a large collection of dictionaries in JSON format obtained through an API request totaling over 1000. How can I develop a script that can loop through all the dictionaries and extract the values from one specific key-value pair? For instance: "te ...

Image Handpicked by JCrop User

Successfully implemented JCrop example code for selecting an area on an image with a preview and getting coordinates. However, the challenge lies in allowing users to select an image from their file system, display it in the browser, and perform the afore ...

Incorporating external JavaScript files into a React Element

I am currently revamping my Portfolio Site to incorporate modals into one of the pages as part of the transition to a Single Page Application (SPA). The JavaScript code for these modals is stored in a "main.js" file, and the necessary tags are included in ...

Struggling to fix the excess white space appearing underneath my website

I am new to HTML/CSS and I'm currently working on adding a timeline to my website. However, I've encountered a strange issue with the #timeline class where there is an odd block of space below it whenever I try to adjust the height. So far, I ha ...

Not motivated to write HTML content

Recently, I've been utilizing the lazySizes plugin for optimizing my images. However, I encountered an issue when trying to implement it for HTML content display. Is there a simpler way to achieve this and maintain my current HTML structure? $(&apo ...

Tallying the number of words delimited by a comma

Here is how my counter function is structured: function count() { var value = ids.val(); return (value == '') ? 0 : value.replace(/\s,?|,$/g, '').split(',').length; } After checking the returned value, data is ...

Issue with passing props to screen not displaying on initial load

Greetings, I'm a newcomer to the world of react native and currently facing an issue: const Tab = createMaterialTopTabNavigator(); export const CurriculumMenu = ({navigation, item}) => { const data = item.Title; console.log(data) return ( ...

Resetting the Countdown Clock: A Transformation Process

I have implemented a countdown timer script that I found online and made some adjustments to fit my website's needs. While the current setup effectively counts down to a specific date and time, I now require the timer to reset back to a 24-hour countd ...

Execute a function using a click event within a statement

Is it possible to trigger a function with parameters based on the result of a statement? For example, can we achieve something like this: (click)="datavalue.elementDataCollection.length > 1 ? AddNewDialog (datavalue,datavalue.COCLabel,mainindex,i) : r ...

The supertest request body cannot be found

Testing my express server POST endpoint using supertest has been a challenge for me. Although everything works perfectly in postman, I encountered an issue when trying to pass body parameters into the test. It seems like the body parameters are not being p ...

Should I avoid declaring global app variables in Angular?

After browsing several examples online, I have come across a common pattern in AngularJS code. The basic structure involves creating a new module using the angular.module() method and then retrieving it in other files within the same module. var app = ang ...

Stop Ajax from activating jQuery function

Upon examining our Drupal site, we discovered a straightforward jQuery script that inserts a div class containing content: (function($) { Drupal.behaviors.myHelpText = { attach: function (context, settings) { //code begins //adjusting placeholder ...

What is the best way to align a div with a fixed width in the center, when it is positioned between two other divs within a parent

I have this HTML (technically JSX) code snippet here: https://i.sstatic.net/jXYz0.png The center div with the class domain-input-parent is supposed to have a fixed width of 400px and stay centered horizontally on the screen. This arrangement ensures that ...

Load image asynchronously using a mirror server in React/Next.js with a set timeout time

For my website, I have decided to store all of my images on IPFS, which are pinned successfully. This has helped reduce traffic and keep costs within the free tier offered by my hosting provider. However, at times the IPFS url may not load fast enough dep ...

Using jQuery Flot to dynamically load data onto the x-axis from an array

I have a jQuery flot graph that loads the x-axis data as follows: xaxis: { tickColor: 'transparent', tickDecimals: 0, ticks: ticks }, When I manually set the ticks variable like this, everything works fine and the x-axis displays the 7 da ...

Process JSON data from an input using Javascript

I am encountering an obstacle at the final step of my data flow process. Currently, I am in the midst of developing an application that retrieves input from an HTML form field and utilizes Ajax to fetch data relevant to the user's input. Allow me to e ...

Correctly executed $.Ajax and $.Post requests consistently yield errors when sent from C#

I'm struggling to create a cross-domain web API method in C# that will return valid jsonp to Javascript. Despite returning valid JSON data, I keep encountering failure messages when trying to debug with F12 dev tools or Firebug. Here is my current co ...

Using AJAX (jQuery) to process and refine JSON data through filtration

I need assistance with filtering a JSON array using AJAX but I'm unsure of how to proceed. { posts: [{ "image": "images/bbtv.jpg", "group": "a" }, { "image": "images/grow.jpg", "group": "b" }, { "image": "images/tabs.jpg", ...