0

I'm creating a div with a span on the spot using jquery, like so

$("[data-modal]").click(function(event) {
    event.preventDefault();

    var container = $("<div></div>").addClass("modal m-form").appendTo(document.body);
    var close = $("<span></span>").addClass("modal-close").appendTo(container);
}

so far so good...

Then, i'm binding an event to the selector modal-close, like so

$(".modal-close").click(function(event) {
    alert("close the dialog");
});

That one doesn't work, so i've tried this one, with no success:

$(".modal-close").on("click", function(event) {         
    alert('close the dialog');
});

What am i doing wrong?

Marco
  • 2,687
  • 7
  • 45
  • 61

2 Answers2

1

You have to bind it to the next static parent. Means if you have a parent element that never gets changed, bind it to this (in your case maybe a wrapper for the whole modal). If you haven't a static wrapper around, you can also bind it to the document:

$(document).on('click', '.modal-close', function(event) {
    alert("close the dialog");
});
damian
  • 5,314
  • 5
  • 34
  • 63
0

To bind event to dynamically created element you can use .on(). You have used .on() incorrectly, please check below code -

$(document).on("click",".modal-close", function(event) {
    alert("close the dialog");
});

More Information for .on()

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57