Toni Au Toni Au - 5 months ago 19
jQuery Question

How to associate buttons with new objects (object nesting) in Javascript

So I need something similar to Facebook Messenger's gear button which can be seen only when a conversation box is hovered or is currently active (just to give an image to these words), but how can I associate the button to that object? The object nesting is really confusing me. This is what mine looks like right now.

table_data {

item_1: { fruits: [ {}, ..., {} ]},
item_2: { fruits: [ {}, ..., {} ]},
...
...
item_n: { fruits: [ {}, ..., {} ]},
}


Each
item
is a
div
that has 3 buttons:


  1. Delete - deletes item and all content

  2. Options - opens popover options menu

  3. Expand - expands current
    item
    to show
    fruits
    array of objects



The user enters in a new
item
and then has the option to add objects to
fruits
array.

document.getElementById("save").addEventListener("click", function() {
table_data[newItem] = { fruits:[] };
appendHTML(newItem);
// helper function that appends HTML
}


So under options, user can "Add Fruits". How can I associate that "Add Fruits" to the correct item since the "Options" button is just appended HTML.

If it helps, the helper function looks like this.

function appendHTML(item) {
$("#list").append('<li class="enter"><div class="listContent"><a href="#" class="close"></a><span class="itemName">'+item+'</span></a><a href="#" id="expand"></a><a href="#" id="gear"></a></div></li>');


}

If anyone happens to need an answer to this in the future...

$(document).on('click', "#list > li > .listContent > .gear", function() {
$(this).next().slideToggle();
});

Answer

This is a duplicate of this question. There, you will find multiple answers. I think the best would probably be storing the element in a var and then you can easily target it with whatever you want after you append it