It appears that JavaScript has the capability to automatically remove event listeners from textareas

Greetings to all members of the community,

I have developed a web application (see code below) that, when double-clicked, inserts a text area into the frame.

Upon double-clicking the text area, it changes its color to green, and with another double-click, it reverts back to white...and so forth.

The issue I am facing is that when multiple text areas are created, only the most recently generated one retains the toggleable property. It appears that the event handlers for the preceding text areas are somehow being detached.

How can I ensure that the event handlers remain attached to every single text area?

Your assistance is greatly appreciated :)

function randomIntInRange(min, max) { // min and max included
  return Math.floor(Math.random() * (max - min + 1) + min);
}

// Add a double click event listener to the root container
document.getElementById('root_container').addEventListener('dblclick', function(event) {
var textArea = new TextArea();
textArea.insertIntoHTML(event.clientX, event.clientY);
});

class TextArea {
constructor() {
// Generate a text area id
this.id = randomIntInRange(1000000000, 9999999999);

// Create a variable for changing the text area's bg-color in the onDoubleClick(event) method
this.isToggled = false;
this.onDoubleClick = this.onDoubleClick.bind(this);
}

insertIntoHTML(x, y) {
// Insert a new text area into the html code
document.getElementById('root_container').innerHTML += '<textarea id="' + this.id + '"></textarea>';

// Set the position of the text area
document.getElementById(this.id).style.position = 'absolute';
document.getElementById(this.id).style.left = x + 'px';
document.getElementById(this.id).style.top = y + 'px';

// Add a double click event listener to the text area
document.getElementById(this.id).addEventListener('dblclick', this.onDoubleClick);

// Focus on the text area
document.getElementById(this.id).focus();
}

onDoubleClick(event) {
// Prevent event bubbling
event.stopPropagation();

/* ******************************************
* Toggle the text area's background color
****************************************** */

// If the text area is not toggled yet
if (!this.isToggled) {
// Set the background color to green
document.getElementById(this.id).style.backgroundColor = '#7ce717';
this.isToggled = !this.isToggled;
} else {
// Otherwise set it to white
document.getElementById(this.id).style.backgroundColor = '#ffffffff';
this.isToggled = !this.isToggled;
}
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

#title {
position: absolute;
top: -20px;
left: 200px;
}

#root_container {
background-color: #797979;
width: 100vw;
height: 100vh;
overflow: hidden;
}

.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Set the webpage's title -->
<title>Web App</title>
<!-- Include the cascading style sheet -->
<link rel="stylesheet" type="text/css" href="../css/styles.css">
</head>
<body>
<div id="root_container">
</div>
<!-- Include the javascript file -->
<script src="../javascript/behaviour.js"></script>
</body>
</html>

Answer №1

When you reach this point in your code:

document.getElementById('root_container').innerHTML += '<textarea id="' + this.id + '"></textarea>';

You are essentially destroying the existing DOM elements and then reinserting them. This process removes old TextAreas and detaches any associated events.

Instead of using innerHTML, consider creating a new element and appending it to your container using appendChild.

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

How can I retrieve the value from req.body following an AJAX POST request on the server side with Express?

Currently, I am utilizing AJAX to send JSON data: app.use(express.json()); app.use(bodyParser.urlencoded({extended:true})) app.use(express.urlencoded({ extended: true})); const rowObject=JSON.stringify(rowData) $.ajax({ type: "POST&q ...

When hovering over an object in three.js, the cursor should change on mouseover

In my scene, I have added a sphere and plane geometry. Clicking on the plane geometry will open a linked website. Now, when hovering over the plane geometry, I want the mouse cursor to change to a hand pointer icon, and revert back to its original style ...

An issue occurred when trying to access the version information from http://localhost:8088/web/webclient/version_info while logging in to the Odoo server using

While attempting to log in with my Ionic app to an Odoo server, I encountered the following error message. Is this due to CORS, and how can I configure my local Odoo server without using Nginx? XMLHttpRequest cannot load http://localhost:8088/web/webcli ...

Obtain the RadNumericTextBox value using JavaScript or jQuery in an ASP.NET environment

In my ASP.Net Web Page, I have a RadNumericTextBox within a DetailsView. I am attempting to access this element in JavaScript using jQuery. Despite successfully obtaining the RadNumericTextBox as a variable in JavaScript and verifying that it contains all ...

Unable to instantiate a class using a module in React

I am on a mission to combine Monaco editor and Convergence in order to create a collaborative editor. To achieve this goal, I am referencing the following repositories and examples: https://github.com/convergencelabs/monaco-collab-ext https://github.com/c ...

The form submission did not yield any results

function calculateCost() { var projectorCost=0,price=0,quantity=0,discountPrice=0,totalCost=0; var modelName=document.getElementById('projectormodel').value; var quantity=document.getElementById('q ...

Adjust transparency in Bootstrap slider with picture indicator

Currently, I am in the process of creating an HTML page featuring a Bootstrap carousel. To enhance user interaction, I have replaced the standard selector with images that, when clicked, will transition the slider to display corresponding content. In orde ...

Navigation Menu Spanning Across Full Width of All Screens

Hello! I am currently working on designing a responsive menu using HTML5 and CSS. My approach involves creating a navigation menu for desktop computers and implementing a checkbox with a label to reveal the responsive menu when needed. Here is the code s ...

Unable to properly cancel a post request using abort functionality

In the process of building a Next.js app, I encountered an issue with calling a post request. I included a cancel button to halt the post request, and attempted to use abortController in conjunction with Axios (v1.4.0) to achieve this. Even though the &ap ...

Managing content in two separate divs at the same time using AJAX

I am curious to know how I can achieve a functionality where editing the text field on the left will automatically update the text field on the right. I have a feeling that it involves using AJAX, and I would like to implement it as well. Can anyone guid ...

What is the method for implementing two-way binding on a checkbox in Angular?

Within my accordion, I have a series of options in the form of checkboxes. Users are able to select these checkboxes, but I am seeking a way to pre-select certain checkboxes based on specific conditions. The challenge arises when these conditions are deter ...

Using jQuery's .load() method is like including a file in a

Currently, Im working on revamping a company website that comes equipped with its very own CMS. Unfortunately, we are restricted from accessing the server configuration and FTP, which means I am limited to running only client-side files like HTML/CSS/J ...

How can you effectively pass props to a Vuejs Component that is rendered by a Router?

I am new to Vuejs, so I apologize if this is a beginner question. I have added a router to my App and I want to display data from my main App in my Components templates, but it doesn't seem to be working. Here is my current setup: Vue.use(VueRouter ...

Personalized FullCalendar header title

Is there a way to display a unique header title for each calendar in my collection of 16? I've been trying various modifications to the code snippet below with no success: firstDay: <?php echo $iFirstDay; ?>, header: { left: 'prev,next ...

Having trouble with AngularJS $location.path() not redirecting properly?

Why am I unable to redirect to a different URL using $location.path in angular.js? .controller('CheckCtrl', function($scope, $localStorage, $location) { $scope.check = function(){ if($localStorage.hasOwnProperty("accessToken") === t ...

Enhance the appearance of rows in a table by adding a captivating marquee effect to those with

I'm working with a table that has 7 rows and 2 tabs for Sunday and Monday. The row corresponding to the current time is highlighted in red. I wanted to know if it's possible to add the following <marquee>My first Row</marquee> effe ...

Transferring information from MySQL to Vue.js data attribute

I have retrieved some data from MySQL and I am looking to integrate it into a vue.js data property for seamless iteration using v-for. What is the ideal format to use (JSON or array) and how can I ensure that the data is properly accessible in vue.js? &l ...

Utilizing HTML5 audio elements with jQuery enhances the auditory experience

As I delve into creating a simple media section for a website, I have encountered some challenges that I would like to address. Let me explain the issue I am facing. I currently have a 'play list' consisting of 'links' - represented by ...

Guide to setting up an automated process in PHP

When setting up a tournament interface on my page: Users utilize functions like fopen() and fwrite() to create tournaments. The created tournaments must only start after a specific time, for example, 1 hour. This delay allows other users to join the tour ...

Saving Selected Radio button values into Jquery Array

In my HTML table, there are multiple rows with radio buttons representing the sexes in the 0th position of <td>. I am trying to store the values of sex (either 1 or 0) in an array. Below is a snippet for a table with 3 rows. HTML Code: <table> ...