Trying to attach a click event to a dynamically created image to trigger a modal to close

2.1k views Asked by At

I've got a bit of code (full disclosure - not 100% my own code) that works to open and close a modal dialog box but when I try to attach a click event to several images it doesn't seem to work.

Here's the relevant working code:

 var modal = (function(){
    var 
    method = {},
    $overlay,
    $modal,
    $content,
    $close;

    $overlay = $('<div id="overlay"></div>');
    $modal = $('<div id="modal"></div>');
    $content = $('<div id="modalcontent"></div>');
    $close = $('<a id="modalclose" href="#">close</a>');

    $modal.hide();
    $overlay.hide();
    $modal.append($content, $close);

    $(document).ready(function(){
       $('body').append($overlay, $modal);
    });

   // Center the modal in the viewport
    method.center = function () {
        var top, left;    
        top = Math.max($(window).height() - $modal.outerHeight(), 0) / 2;
        left = Math.max($(window).width() - $modal.outerWidth(), 0) / 2;
        $modal.css({
        top:top + $(window).scrollTop(), 
        left:left + $(window).scrollLeft()
    });
};

// Open the modal
method.open = function (settings) {
    $content.empty().append(settings.content);

    $modal.css({
        width: settings.width || 'auto', 
        height: settings.height || 'auto'
    })

    method.center();

    $(window).bind('resize.modal', method.center);

    $modal.show();
    $overlay.show();
};

// Close the modal
method.close = function () {
    $modal.hide();
    $overlay.hide();
    $content.empty();
    $(window).unbind('resize.modal');
};

$close.click(function(e){
    e.preventDefault();
    method.close();
});

    return method;
  }());

This code gets called as part of this:

          $('#snaptarget .tile').doubletap(
              /** doubletap-dblclick callback */
              function(event){
                  $.get('logic/get_swatches.php?id='+newID, function(data){
                      modal.open({content: data});
                  });
              },
              /** doubletap-dblclick delay (default is 500 ms) */
              400
          );

...which works to open up the modal with a selection of fabric swatches (with code that matches a swatch to a frame on click).

The existing code creates a small button in the top-right of the dialog that can be clicked to close the dialog but I want it to close automatically upon a user clicking (i.e. selecting) any fabric swatch.

I've already tried using several variations of this:

$('.swatchAsCloseButton').on ('click', function(e){
    method.close();
});

and

$('.swatchAsCloseButton').click(function(e){
     method.close();
);

but none seem to work at all. I'm entirely self-taught and mostly a PHP person - I'm sure that I'm missing something very basic but I can't find it and all the search results seem to be simple stuff that are solved with $('.class').on() and $('.class").click().

*****edit: working now. Because the #modal div and all contents are dynamically generated I had to go all the way back to the body element as the static element. My mistake was in thinking that the 'parent' element could work in place of the 'static' element given in the solutions I was finding while searching. Here's the change I made that worked:

$.get('logic/get_swatches.php?id='+newID, function(data){
                      modal.open({content: data});
                      $('body').on ('click', '#modal #modalcontent .swatchAsCloseButton', function(e){
    modal.close();});
1

There are 1 answers

3
Dickens A S On BEST ANSWER

If you are creating a any element on the fly you should either rebind the event or you should use event-delegation in jquery

Duplicate Event binding on dynamically created elements?

Try to call unbind and bind the event

$('.swatchAsCloseButton').unbind('click');
$('.swatchAsCloseButton').click(function(e){
    method.close();
);