I am having an issue with some jQuery I wrote, below. Basically, sometimes my final two steps appear to run, and sometimes they don’t. I believe this is because the load() function is taking a variable amount of time to complete.
Let me walk you through quickly. I have an unordered list with each LI having an onclick event of “changeTabContent”. When the page loads, I trigger the active LI’s click.
On a click, first thing I do is remove the previous results, which are a UL living under the “li.active” element. Next, I move the “active” class to the LI that was pushed and off the old one. Next, I add a loading animation to the screen. Next I append a new UL to the new “li.active” and use the load() method to insert a bunch of LI’s from a different page. onSuccess, I remove the loading animation. [note 1]
Next, you’ll see a hack I added, more on that in a minute…
Last two steps are to add a “more” link to the bottom of the returned li’s, if a link was passed into the function, and finally I remove a handful of LI’s (excluding more link) so there are only “x” on the screen.
My #1 problem is that the more link is not showing up at times, and the cleanList function is not removing LI’s. I believe the problem is that with the load being async, sometimes those last two steps are being hit, but there is no LI’s in the DOM yet. You can see I tried to run a hack so the while loop will execute when there is no “ul” yet.
[note 1] - I tried to add the final two steps into the load() callback, but the LI’s were NEVER loaded in the DOM when the callback function was executed.
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".tabbed-dynamic-content li.active").trigger('click');
});
function changeTabContent(element,strURL,strMoreURL) {
//remove results UL if there
$(".tabbed-dynamic-content ul li.active ul").remove();
//change active class to button pushed
$(".tabbed-dynamic-content ul li.active").removeClass("active");$(element).addClass("active");
//add loading image, remove on callback of load()
$(".tabbed-dynamic-content").append(
'<div class="ajaxLoading"><img src="ajax-loader.gif" alt="loading animation"></div>'
);
//make ajax call
$(".tabbed-dynamic-content ul li.active").append($('<ul>').load(strURL + " ul.results li",
function() {
//remove loading image
$(".tabbed-dynamic-content .ajaxLoading").remove();
}
));
//this is a hack to wait for the load to finish (when the <ul> will appear in the DOM)
while ($(".tabbed-dynamic-content ul li.active ul").length == 0) {}
//add more link
if (strMoreURL!='') {
$(".tabbed-dynamic-content ul li.active ul").append('<li class="moreLink"><a href="'+strMoreURL+'">more</a></li>');
}
//clean the results
cleanList();
}
function cleanList() {
var intMaxResults = $(".tabbed-dynamic-content #ssMaxResults").val()-1;
$(".tabbed-dynamic-content ul li.active ul li:gt(" + intMaxResults + "):not(.moreLink)").remove();
}
</script>