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

Piotr Połaniecki
PLUS
Piotr Połaniecki
Courses Plus Student 3,181 Points

[SOLVED] event.preventDefault() stopped working?

Hey guys, I need another pair of eyes. Everything was working fine until I added a code that ads caption to the image. After doing that my browser seems to be ignoring event.preventDefault() method and it's taking me to a dead end. I double checked and everything seems to be fine. Please help me out, it's so frustrating.

Here's my code, maybe You guys can find a bug. Thanks!

// Problem: user when clicking on image goes to a dead end=poor UE
// Solutioin: create an overlay with the large image - Lightbox
var $overlay = $("<div id="overlay"></div>");
var $image = $("<img>");
var $caption = $("<p></p>");


// Add umage to overlay
$overlay.append($image);

// Add caption to overlay
$overlay.append($caption);

// Add an overlay
$("body").append($overlay);

// Capture the click event on a link to an image
$("#imageGallery a").click(function(event){
    event.preventDefault();
    var imageLocation = $(this).attr("href");
  // Update overlay with the imge linked in the link
    $image.attr("src", imageLocation); 

  // Show the overlay  
    $overlay.show();

  // Get child's alt attribute and set caption
    var captionText = $(this).children("img").attr("alt");  
    $caption.text(captionText);

});


//3. When overlay is clicked 
$overlay.click(function() {
  //3.1 Hide the overlay.
  $(this).hide();

});

2 Answers

Chris Davis
Chris Davis
16,280 Points

One issue that i see is your $overlay variable var $overlay = $("<div id="overlay"></div>");

When you require quotes within your jQuery selector you have to either use single quotes on the attribute value or escape the double quotes...

var $overlay = $("<div id='overlay'></div>");

or

var $overlay = $("<div id=\"overlay\"></div>");

Hope that helps :thumbsup:

Piotr Połaniecki
PLUS
Piotr Połaniecki
Courses Plus Student 3,181 Points

Hi Chris,

indeed, that was the issue! Normally I use single quotes but because I am a novice and saw in the video that Andrew was using double quotes, I decided to change them all and forgot to use backslash. So silly mistake!

Thanks a lot for your help!