I am loading content from a series of links like this :
<div id="tagList" style="display: block;">
<ul class="post_tags">
<li id="barrow" class="count-1"><a class="barrow" title="Barrow Tag" href="#Barrow">Barrow</a></li>
<li id="carnies" class="count-3"><a class="carnies" title="Carnies Tag" href="#Carnies">Carnies</a></li>
</ul>
</div>
These then open up a series of images with ajax loading the relevant page, that function looks like this :
$('#tagList li').each(function() {
$(this).click(function() {
var tagName = $(this).attr("id");
var tagURL = '<?php bloginfo( 'url' );?>/tag/' + tagName;
var toLoad = '<?php bloginfo( 'url' ); ?>/tag/'+ tagName + ' .tagTable';
function loadThemTags(){
$('#tagThumbs').load(toLoad,hideLoader);
};
function hideLoader(){
$('.tagTable').fadeIn('slow');
};
loadThemTags();
});
});
The content that is loaded in .tagTable looks like :
<ul id="tagImgBox">
<li class="466">
<div style="display:none" class="466_link">http://foo.com/portfolio/louie</div>
<img class="tagInfoTrigger" alt="Louie" src="http://foo.com/wp-content/themes/Loupe/scripts/timthumb.php?src=/wp-content/uploads/2011/08/louie.jpg&w=80&h=80&zc=1">
</li>
<li class="418">
<div style="display:none" class="418_link">http://foo.com/portfolio/devo-and-seigfried</div>
<img class="tagInfoTrigger" alt="Devo and Seigfried" src="http://foo.com/wp-content/themes/Loupe/scripts/timthumb.php?src=/wp-content/uploads/2011/06/devo_siegfried_2.jpg&w=80&h=80&zc=1">
</li>
</ul>
I want to work with the link that is printed in the hidden div. I have this script :
$('#tagImgBox li').each(function(){
$(this).click(function(){
var uc = $(this).attr('class');
var uc = uc + "_link";
var up = $('.' + uc).html();
alert (up);
});
});
which works if I navigate straight to the /tag/ page. But if I access the ajax loaded .tagTable they do not work. Nothing happens, even break points are ignored. It is as if #tagImgBox li does not exist but I can see the id is there when pulled through the ajax.
Hope my question makes sense and thanks for any help!
You need to use
.live()instead of.click().The code you have now only attaches the click handler to the selected elements when you run it. What you want to do is have the click handler attached to all elements that match no matter when they show up (so, this means things that are loaded via AJAX after the page has finished loading initially).
Here’s the code you should use:
You also don’t need
.each()(using.live()or.click()) because event handlers will attach to each selected element by default. In fact, most jQuery methods behave this way.By using
.live(), you will be able to load elements that match and have the handler attach to them automatically.