0

I have simple script which make layer on background when popup div is shown.

jQuery(".openForm").click(function() {    
    jQuery("#popup").show();
    jQuery("body").append('<div id="layer"></div>');
});

This works fine but, when I click somewhere it should close popup with this script

jQuery("#layer").click(function() {    
    jQuery("#popup").hide();
    jQuery("#layer").remove();
});

anyway nothink happens, there is no error even.

user3175393
  • 109
  • 1
  • 10
  • What does your HTML look like? Where are you binding the event? Is it after the element exists? Do you have multiple elements with the same ID (you can't do that). – gen_Eric Jan 29 '14 at 21:47
  • possible duplicate of [Events triggered by dynamically generated element are not captured by event handler](http://stackoverflow.com/questions/12829963/events-triggered-by-dynamically-generated-element-are-not-captured-by-event-hand) – Felix Kling Jan 29 '14 at 21:51
  • and [Event binding on dynamically created elements?](http://stackoverflow.com/q/203198/218196) – Felix Kling Jan 29 '14 at 21:51

1 Answers1

3

I'm guessing #layer doesn't exist when you attempt to bind the handler. Use event delegation instead:

jQuery(document).on('click', "#layer", function() {    
    jQuery("#popup").hide();
    jQuery("#layer").remove();
});

Alternatively, you could hide/show the #layer div (like the #popup div) instead of adding and removing it each time.

Jason P
  • 26,984
  • 3
  • 31
  • 45