Nyxynyx Nyxynyx - 6 months ago 14
Javascript Question

Unable to select div (generated dynamically) using jQuery

I have a popup box that retrieves content data via AJAX and displays this content. This is taken care of by the asynchronous function

generateInfoboxContent()
and the HTML content retrieved is
boxText
. The content that will be displayed depends on the item that was clicked by the user.
infoboxes[i].setContent
and
infoboxes[i].open()
are functions that add the content to the HTML page.

Problem: I want to select a div
infobox_header_favorite
within this dynamically generated content
boxText
using jQuery using
.click()
but the click handler does not seem to be triggered! How can I solve his problem?

jQuery Code

(function(i) {
var boxText = generateInfoboxContent(infoboxes[i].listing_id, function(boxText) {
infoboxes[i].setContent(boxText);
infoboxes[i].open(map, markers[i]);
infoboxes[i].show();
infoboxes_open.push(infoboxes[i]);

console.log('Hello');
// Favorite function
$("#infobox_header_favorite").click(function() {
console.log('favorite!');
toggleFavorite(infoboxes[i].listing_id);
});
});
})(i);


Result

Hello
is written to the console, but
favorite!
is not written to the console log when the div
infobox_header_favorite
is clicked.

UPDATE

jQuery Code

$.getJSON(base_url + 'index.php/main/getplaces',
{ data: data },
function(json){


for( i = 0; i < json.length; i++) {

(function(i) {
var boxText = generateInfoboxContent(infoboxes[i].listing_id, function(boxText) {
infoboxes[i].setContent(boxText);
infoboxes[i].open(map, markers[i]);
infoboxes[i].show();
infoboxes_open.push(infoboxes[i]);

console.log('Hello');
// Favorite function
$("#infobox_header_favorite").click(function() {
console.log('favorite!');
toggleFavorite(infoboxes[i].listing_id);
});
});
})(i);

}


});


UPDATE 2

for( i = 0; i < json.length; i++) {

(function(i) {
var boxText = generateInfoboxContent(infoboxes[i].listing_id, function(boxText) {
infoboxes[i].setContent(boxText);
infoboxes[i].open(map, markers[i]);
infoboxes[i].show();
infoboxes_open.push(infoboxes[i]);

console.log('Hello');
// Favorite function
$("#infobox_header_favorite").on("click", function() {
console.log('asd');
toggleFavorite(infoboxes[i].listing_id);
});
});
})(i);

}


Received an error
Uncaught TypeError: Object [object Object] has no method 'on'

xyz xyz
Answer

Use .live() or .on() to bind event to dynamically added elements.

.live() is deprecated in jQuery 1.7

Comments