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

preventDefault not working

I am trying to create a page that exports my latest instagram pictures, and when clicked displays a lightbox, but I can't seem to get prevent default to work. It works if I try it on a different link on the page. Help please? Thx

You can see the site here: https://port-80-caque7bh7l.treehouse-app.com/ Here is my code:

///CREATE OVERLAY WHEN CLICKED
$(document).ready(function(){
$('.overlay').hide();
$('#instafeed a img').on('click',function(event){
  event.preventDefault();
  $(this).hide();
});
});

3 Answers

Ryan Field
PLUS
Ryan Field
Courses Plus Student 21,242 Points

The clicking action actually happens on the anchor element, so you might just need to use:

$('#instafeed a').on('click',function(event){
  event.preventDefault();
  $(this).hide();
Adrian Randall
Adrian Randall
4,807 Points

Try this, I modified it on your site and seemed to do the trick, be more specific though instead of just 'img' like I have

$(document).ready(function(){ $('.overlay').hide(); $('img').on('click',function(event){ event.preventDefault(); $(this).hide(); }); });

I tried this:

$(document).ready(function(){
  $('.overlay').hide(); 
  $('#instafeed a img').on('click',function(event){ 
    event.preventDefault(); 
    $(this).hide(); 
  }); 
});

It still doesn't seem to be working. Any ideas?

I tried this:

$(document).ready(function(){
  $('.overlay').hide(); 
  $('#instafeed a img').on('click',function(event){ 
    event.preventDefault(); 
    $(this).hide(); 
  }); 
});

It still doesn't seem to be working. Any ideas?