Update: problem solved:
Since 'problematic' elements were being created after the moment the page loadad, event delegation made sure all of them were bound to the jQuery event.
Original post:
I got this piece of code:
while ($row=mysqli_fetch_array($res)){
if($cont>3){
$cont=1;
$txt=$txt.'</tr><tr>';
}
$txt=$txt.'<td>';
$txt=$txt.'<figure><img src="'.$row['picture'].'"/></figure>';
$txt=$txt.'<figcaption>'.$row['pictureDesc'].'</figcaption>';
$txt=$txt.'<div class="dialogInfoOpener" style="border:solid red 1px;">Details</div>';
$txt=$txt.'</td>';
$cont++;
}
$txt=$txt.'</tr>';
echo $txt;
It is part of a PHP file that works along with a JS file (Ajax) in order to "construct" a table by rows of 3 cells, by concatenating strings. For each cell, some data is loaded from a database. Each cell places a div
with a given class (dialogInfoOpener
) and certain inline style. The div
element should be clicked on in order to open a jquery Dialog box - this where the problem begins.
The code for my Dialog box:
HTML
<div id="dialogInfo" title="Product description">Info to be put in here.</div>
jQuery
$("#dialogInfo").dialog({
autoOpen: false,
buttons:[{
text: "Close", click :
function(){
$(this).dialog("close");
}
}]
});
$(".dialogInfoOpener").click(function(event){</s>
$("#dialogInfo").dialog("open");</s>
});</s>
The code works wonderfully for any element with class dialogInfoOpener
that is found on the page, EXCEPT for any div
elements that belong to the table that was just constructed. When clicking on these divs, it won't do anything (class and style attributes are set correctly for each cell). It appears that jQuery is not responding to the class names given to the divs. Why?
I hope it is clear.
I'd appreciate any helpful suggestions.
As these elements were dynamically created, you could use event delegation, e.g:
$(document).on("click", ".dialogInfoOpener", function(event){
$(".dialogInfo").dialog("open");
});
There's usually a better selector to use than document
- find a consistent parent element of .dialogInfoOpener
elements and use that instead.
Also, I think you may have a typo - your HTML mentions elements with #dialogInfo
, but inside your click function you are using .dialogInfo
? Remember that ID's need to be unique, if you have more than one, just use a class.