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.

3

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You'll probably want to remove the click handler from the document after the modal is closed.
@natewiley No, bind it once when the page loads, then leave it there.
i dont like messy html code so i remove things which are only for some reason with no specific content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.