Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript jQuery Basics (2014) Creating a Simple Lightbox Perform: Part 4

zachary adams
zachary adams
8,365 Points

Why won't the fadeIn() work for the first image that I click, but after it works how I want it to?

here is my code:

//Problem: User when clicking on image goes to a dead end
//Solution: Create an overlay with the large image - Lightbox

//declared variables
var $overlay = $('<div id="overlay"> </div>');
var $image = $("<img>");
var $caption = $("<p></p>");
var $presentation = false;

//appended html elements after the overlay
$overlay.append($image);
$overlay.append($caption);
//append the overlay to the body so it will take up the whole screen
$("body").append($overlay);

//capture the click event on an image
$("#imageGallery a").click(function(event) {
  //set presentation to true
  $presentation = true;
  //if true
  if($presentation === true)
  {
  //prevent default image location
  event.preventDefault();

  var imageLocation = $(this).attr("href");
  $image.attr("src", imageLocation); 

    $overlay.show();
      var captionText = $(this).children("img").attr("alt");
      $caption.text(captionText);
      $image.fadeIn("slow");
      $caption.fadeIn("slow");
      presentation = false;
 }//end if statement

});
//show the overlay
//if the overlay is clicked
$overlay.click(function(){
      $presentation = false;
      $overlay.hide();
      $caption.fadeOut("fast");
      $image.fadeOut("fast");

});

1 Answer

zachary adams
zachary adams
8,365 Points

thanks man, thought it was something with my JavaScript. Didn't think to check the CSS. Either way thanks