Sergi
Sergi

Reputation: 1240

.each() skipping the first item

I'm having some strange behavior with this function that given an HTML file (loaded asynchronously into a gallery everytime we click a link) makes each element ("opacityLayer") in that HTML file appear one by one.

The function is called as the document loads, on this first case it does what it's supposed to do and it gives every "opacityLayer" element, the "opacityLareIn" class, one by one, every 300ms. But when I click on a new link, it loads the new HTML file, and it skips the first "opacityLayer" element which I don't understand. Added comments on my code as well.

$(document).ready(function(){

//runs the function as the document is loaded.
showThem();

/* The function, gives every opacityLayer element,
the class of opacityLayerIn, by order, every 300ms */
function showThem(){
  $(".opacityLayer").each(function(i) {
    setTimeout(function() {
      $(".opacityLayer").eq(i).addClass("opacityLayerIn");
    }, 300 * i);
  });
}

/* The list where my links are, everytime a link is clicked
   it's data value it's used as a parameter for the loadContent function */
$(".categoryList").on("click", function(e){
  var target = $(event.target).attr('data-name');
  $(event.target).addClass("selected").siblings().removeClass("selected");
  loadContent(target);
 })

/*The loadContent function loads the HTML files into the gallery and
  calls the showThem function, but when the new content loads, the
  first element is being skipped */
function loadContent(value){
  $(".gallery").load(value +".html");
    showThem();
    $("#mainSectionTitle").addClass("animate-inLeft");
    $(this).siblings().removeClass("selected");
    $(this).addClass("selected");
    $(".wrapper h1").text(value);
    setTimeout(timeOut, 700);
}



});

Anyone sees what could be the problem here?

Upvotes: 2

Views: 160

Answers (1)

Cave Johnson
Cave Johnson

Reputation: 6778

The content hasn't loaded from the ajax request yet and you are trying to show it before it is loaded. Try using the complete callback parameter of .load(). Pass in your showThem function as a callback function like this:

$(".gallery").load(value +".html", showThem);

Upvotes: 2

Related Questions