Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find out which div was clicked and pass it to the click function handler?

I’m adding a list of child divs (cards) by looping through an array. I want to create an onclick event listener for each child div (card) of parent div (board).

$.each(cardArray, function(i,value){

if(i<9){
  var tCard = $('<div class="cardContainer" title="'+cardArray[i]['name']+'" data-id="'+i+'">'+cardArray[i]['damage']+'</div>')
  $("#area_myCards").append(tCard)
}

});
$("#area_myCards > .cardContainer").on('click',cardClick())
    <div id="area_myCards"></div>

but I’m unsure how to find out which child div was clicked and pass it to cardClick()?
I’m also going to be using the childs data-id within cardClick() and I’d like to know how to get this- should I pass it to the function in the on click listener somehow, or do it within the function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Assuming that cardClick() is defined somewhere else, first of all, you would call it with $("#area_myCards > .cardContainer").on('click',cardClick) (without the parenthesis at the end).

That function would get passed an event as its first argument (usually called e), and the event has a property called currentTarget that can be used to see which instance has been clicked.

From MDN:

The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.

So the cardClick function would be something like:

const cardClick = (e) => {
    const targetInstance = e.currentTarget;
    // Do stuff with your specific card...
    // To access data-id: targetInstance.getAttribute('data-id') 
    // or targetInstance.dataset.id
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading