Determine who the creator of the clicked div is

I'm sorry if my explanation is a bit difficult to comprehend. Here is the code snippet in question:

names.push(newName);
var strName = newName;
var newName = document.createElement('p')
newName.setAttribute('id', newName);
document.body.appendChild(newName);
newName.innerText = strName;
$(newName).css('position','absolute')
$(newName).css('top', y);
$(newName).css('left', x);
updateXY();

When a user creates a new div with a custom name, everything works as expected. However, I am struggling to figure out how to detect when a user-clicks on any of these dynamically created and named divs.

For instance:

If a user creates divs named 'hello' and 'goodbye', I can't simply use $('#hello').click(function() {}); because I won't know which specific div the user chose to create.

Additionally, the array names contains the names of all the created divs, in case that information is helpful. Any assistance on this matter would be greatly appreciated. Thank you.

Answer №1

To make the element interactive, attach an event listener to it just like you would when adding styles:

 $(newName).on("click",function(){
   console.log("element "+$(this).text()+" clicked");
 });

Check out the demo on JSFiddle

Alternatively, you can use JS's addEventListener() method:

newName.addEventListener("click",function(){});

View the example on JSFiddle

For older browsers, you can also use the traditional way of adding click events with onclick:

newName.onclick = function(){};

See the implementation on JSFiddle

Answer №2

Here is an example of how you can achieve this:

$(newName).on("click",function(e){
    // 'e' represents the click event, we can use e.toElement to find out which element was clicked
    var $thisDiv = $(e.toElement);
    // perform actions on $thisDiv
});

Answer №3

Once a div element is created, the next step is to activate the 'click' event on it.

<a class="js-create-div" href="#">Click to Create Div</a>
$(document).ready(function(){
    function initiate(){
      var freshDiv = $(".js-user-div").not(".js-inited");

      freshDiv.on("click",function(){

        alert($(this).html());

      });

      freshDiv.addClass("js-inited");
    }

    $(".js-create-div").click(function(){
    $("#wrapper").append("<div class='js-user-div'>"+Math.random()+"</div>");        
    initiate();
  });
});

Access the JSFiddle link for a visual demo

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

Is it possible to utilize a map in Python or incorporate other advanced functions to efficiently manage indices?

When working with higher order functions in JavaScript, we have the ability to access the element, index, and iterable that the function is being performed on. An example of this would be: [10,20,30].map(function(element, index, array) { return elem + 2 ...

How can str_replace be used in an array?

Is it possible to use an str_replace function within an array? I have a script that retrieves values from a CSV file and inserts them into a MySQL database. However, some cells in the CSV file may contain '-', which signifies no value. The curren ...

Is the behavior of undefined different in Chrome?

Upon examining my Asp masterpage, I noticed the following code snippet: <script> if (theForm !== undefined) { // <<== line 746: error theForm.onsubmit = ...bla bla... ; } </script> When checking the Chrome console, an er ...

What is causing TypeScript to compile and remove local variables in my Angular base controller?

I am trying to develop a base controller in Typescript/Angular for accessing form data, but I'm encountering an issue where the form member seems to be getting removed during compilation and is not present in the generated JavaScript code. Could you ...

What could be causing the issue with the variable appearing as undefined in

My class has a property: public requestLoadPersonal: Personal[] = []; As well as a method: private filterByGender(selectedValue: any): void { console.log(this.requestLoadPersonal); this.requestLoadPersonal = this.requestLoadPersonal.filter( ...

AJAX - Retrieving the server response following a page change by the user

My Understanding: I comprehend that when I make an ajax call to my server, a handler is created, the request is sent, my PHP script receives and processes the request, and sends back a response which my JavaScript can parse. Additionally, I am aware that ...

Adjusting mesh rotation on elliptical curve using mousewheel scrolling

I have arranged several plane meshes in a uniform manner along an elliptical curve. During the animation loop, I am moving them along the ellipse curve using curve.getPointAt with time delta and applying the matrix. Additionally, I am attempting to incor ...

What causes variations in the output of getClientRects() for identical code snippets?

Here is the code snippet provided. If you click on "Run code snippet" button, you will see the output: 1 - p.getClientRects().length 2 - span.getClientRects().length However, if you expand the snippet first and then run it, you will notice a slight dif ...

What is the technique for causing this element to move in reverse?

How can I utilize JS to halt the interval and direct the alien to move backwards once it reaches 700px? I am aware that CSS can achieve this, but I prefer a strictly JS approach. I am struggling with stopping the interval as it hits the left position of 70 ...

What are the steps involved in generating and implementing dynamic hierarchical JSON data structures?

I am currently creating a dynamic diagram using d3.js that incorporates hierarchical data. The goal is to make it interactive so that users can manipulate the hierarchy by adding or removing data values and children. I'm wondering if there is a way to ...

Using Perl's regular expressions to perform substitutions

Within an html file, my goal is to incorporate a link to the numbers that appear within the [ ] in various patterns such as: [1] or [1-2] or [1,3,6] or [1,3,4-6, 9]. While I have managed to match the simple pattern like the first one: $html =~ s`\[&b ...

react-widgets: deciding on the return value for the onSearch function in Multiselect

I'm currently experimenting with react-widgets and utilizing the onSearch function in conjunction with the Multiselect component. Even though I can see that onSearch is being called with the searchTerm, I am unable to incorporate the response into the ...

Emphasizing a full row within a table is a way to draw attention

I have a piece of HTML/CSS code that successfully underlines the text in a single table cell when hovering over it. However, I want to extend this effect to underline all text in a row of cells, rather than just one cell. It's not necessary for the en ...

React - The issue with my form lies in submitting blank data due to the declaration of variables 'e' and 'data' which are ultimately left unused

Currently, I'm working on incorporating a form using the react-hook-form library. Despite following the documentation and utilizing the handleSubmit function along with a custom Axios post for the onSubmit parameter like this: onSubmit={handleSubmit( ...

Attempting to link two JavaScript files, however, only one of them is functioning correctly

I'm currently experiencing an issue with my HTML page that involves calling two JS files for two different image sliders on the same website page. One slider works perfectly fine while the other does not. I'm confused as to whether it's perm ...

I attempted to establish a connection between my backend and the MongoDB database, however, an error was displayed

Error: Failed to establish a connection to the database! MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 Please check the database connection settings and try again. For more information, refer to the error log. ...

Retrieve information from a PHP file using AJAX when the output is just a single line

I never thought I would find myself in this situation, but here I am, stuck. I just need a single result from this PHP file, so is using an array really necessary? Despite my efforts to console.log(result) multiple times, all I get back is "null". What c ...

Angular-ui-bootstrap-tabs feature smooth transitions when switching between tabs, but lacks animation when moving

Just made some updates to an example by user @austin Encountering an issue when trying to transition backwards (from tab3 to tab2), but it works fine when transitioning forward. I'm not sure what I'm missing here, so any help would be appreciate ...

Using Object.create to establish multiple prototypes in JavaScript

I am trying to have my child object inherit the prototypes of multiple parents, but the following methods do not seem to work: child.prototype = Object.create(parent1.prototype, parent2.prototype); and also this: child.prototype = Object.create(parent1 ...

Ways to eliminate white space in bootstrap CSS menu bar

My goal is to create a responsive navigation bar using Bootstrap and customize it to fit my design needs. Although I was able to implement the dropdown on mobile-sized windows, I encountered a margin issue that I couldn't remove on the right side. I ...