Nathan Contini
Nathan Contini

Reputation: 85

Fade out and in images from list

If possible, I could really use some help with my homework. For my current project, we have been tasked with having images from a list above fade when clicked. The captions should also fade out and in with the images. I have the old image and caption fading out, but cannot figure out how to get the new ones to fade in. Code below:

$(document).ready(function() {
  // preload images
  $("#image_list a").each(function() {
    var swappedImage = new Image();
    swappedImage.src = $(this).attr("href");
  });

  // set up event handlers for links    
  $("#image_list a").click(function(evt) {
    var imageURL = $(this).attr("href");
    $("#image").fadeOut('slow', function() {
      $("#image").load(function() {
        $("#image").fadeIn();
      }).attr("src", imageURL);
    });

    var caption = $(this).attr("title");
    $("#caption").fadeOut('slow', function() {
      $("#caption").load(function() {
        $("#caption").fadeIn();
      }).text(caption);
    });

    // cancel the default action of the link
    evt.preventDefault();
  }); // end click

  // move focus to first thumbnail
  $("li:first-child a").focus();
}); // end ready

Upvotes: 0

Views: 87

Answers (1)

Tyler Roper
Tyler Roper

Reputation: 21672

You can ditch .load() in this scenario, as it doesn't seem to be serving a purpose. It's also removed as of jQuery 3.0.

The other thing I'd suggest is to store repeated lookups as variables, rather than continuously doing the same DOM lookups over and over.

$(document).ready(function() {
  var $image_list_a = $("#image_list_a");

  // preload images
  $image_list_a.each(function() {
    var swappedImage = new Image();
    swappedImage.src = $(this).attr("href");
  });

  // set up event handlers for links    
  $image_list_a.click(function(evt) {
    var $image = $("#image");
    var $caption = $("#caption");

    var imageURL = $(this).attr("href");
    $image.fadeOut('slow', function() {
      $image.attr("src", imageURL).fadeIn();
    });

    var caption = $(this).attr("title");
    $caption.fadeOut('slow', function() {
      $caption.text(caption).fadeIn();
    });

    // cancel the default action of the link
    evt.preventDefault();
  }); // end click

  // move focus to first thumbnail
  $("li:first-child a").focus();
}); // end ready

Upvotes: 1

Related Questions