I am creating some thumbnails dynamically with JQuery, like this (in a loop):
var thumb = $('<a class="tinythumb"></a>');
thumb.append('<img src="' + productThumbnailList[i] + '" width="70" height="70" />');
thumbContainer.append(thumb);
Now I’m trying to add some functionality to these via JQuery’s .click(), but I just can’t get it working. I’ve never had trouble trying to do this before, there are no errors and there’s nothing that I can see from my point of view that is incorrect.
I tried this simple .each() to see what would happen. Funnily enough, the rel attribute is being updated, but there’s still no .click() functionality (alert never performed).
$("div#thumbcontainer a").each(function()
{
$(this).attr("rel", "works");
$(this).click(function()
{
alert('never called');
});
});
This is the page I’m trying to work with:
http://burwell.businesscatalyst.com/catalogue/containmentscreen/Enviroguard#
Here’s the entire JavaScript which probably has something relevant in it that’s missing above:
// Properties
var thumbContainer = $("div#thumbcontainer");
var str = thumbContainer.html();
var productThumbnailList = str.split(';');
// Clear thumbContainer of junk HTML
thumbContainer.html("");
// Create thumbnails
if(productThumbnailList.length > 1)
{
for(var i = 0; i<productThumbnailList.length; i++)
{
var large = Math.round(i/2) * 2 == i ? false : true;
// create thumbnail
if(!large)
{
var thumb = $('<a class="tinythumb"></a>');
thumb.append('<img src="' + productThumbnailList[i] + '" width="70" height="70" />');
thumbContainer.append(thumb);
}
}
$("div#thumbcontainer a").each(function()
{
$(this).attr("rel", "works");
$(this).click(function()
{
alert('never called');
});
});
}
Adding an onclick="someFunc()" parameter to the <a> tag makes it call the function fine..
Since you are creating the anchor tag dynamically, use “on” to attach click event handler
http://jsfiddle.net/SUudh/23/
If you are using older version of jquery, use live() or delegate().
http://api.jquery.com/live/