0

I am currently trying with a modal window popup. Essentially it come in and takes over the whole window.

<div id="popup">
    <div id="modal">
        <div id="closeBox"><span id="x">X</span></div>
        <form>
            form stuff..
        </form>
    </div>
</div>

Now when I target my #closeBox like..

$("#closeBox").click(function() {
    $("#popup").remove();   
});

The event never fires. I believe this is because it is nested, if I switched #closeBox to html the event fires and it works, as it does if I switch it to #popup. How can I target the nested element so that it only fires when #closeBox is clicked?

Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
Chris
  • 767
  • 4
  • 8
  • 22
  • Is the popup added dynamically, or in your markup all along but hidden and then made visible? – nnnnnn Mar 09 '15 at 06:48
  • I use `.load()` to bring it in after a `setTimeout` – Chris Mar 09 '15 at 06:48
  • For me it's working as excepted.. See my [DEMO](http://jsfiddle.net/SivaCharan/12kuz9ev/) – Siva Charan Mar 09 '15 at 06:49
  • 1
    If you're using `$("#popup").load(...)` then the `#popup` element exists all along and so can have click handlers assigned to it. But the `#closeBox"` element won't exist until *after* the `.load()` and so can't have a click handler assigned until after the load is complete. Or use a delegated handler: `$("#popup").on("click", "#closeBox", function() { ... });` – nnnnnn Mar 09 '15 at 06:50
  • if the popup is dynamically created, use delegates for binding the events. Otherwise bind the events in document.ready() – Anoop Joshi P Mar 09 '15 at 06:51

1 Answers1

0

Use "delegate" to attach a handler to the DOM element

$( "body" ).delegate( "#closeBox", "click", function() {
  $("#popup").remove();  
});
Cristi Marian
  • 443
  • 8
  • 18