0

I have an 'a' tag, that when clicked, removes the thumbnail from the gallery by calling a jquery click event. But if I dynamically add a thumbnail image and then remove it on the same page without refreshing, the click event doesn't get triggered. It triggers the modal window to pop up (as if I was clicking on the image). Then if I press the 'x' (to close) the modal window THEN triggers the jquery click event to remove the image. It works fine on non dynamically added thumbs or if the page has been refreshed.

$('a.close').click(function () {
    
    var imageId = $(this).attr('id');
    $.post(
            '/ManageSpaces/RemoveImage',
            { id: imageId }
        );
    $(this).parents('li').remove();
});
<div id="row">
  <ul id="sortable">
    @foreach (var image in Model.Images.OrderBy(i => i.Ordering)) {
    <li id="@image.YogaSpaceImageId" class="col-sm-6 col-md-4 imagethumbs" data-yogaspaceid="@Model.YogaSpaceId">

      <div class="thumbnail">
        <a id="@image.YogaSpaceImageId" class="close" href="#">×</a>
        @{ var base64 = Convert.ToBase64String(image.ImageThumbnail); var thumbSrc = String.Format("data:image/gif;base64,{0}", base64); var base64Modal = Convert.ToBase64String(image.Image); var imgSrcModal = String.Format("data:image/gif;base64,{0}", base64Modal);
        var imageId = "pop" + image.YogaSpaceImageId; var imagesourceId = "imagesource" + image.YogaSpaceImageId; }
        <a class="image" id="@imageId" href="" data-toggle="modal" data-target="#myModal">
          <img id="@imagesourceId" src="@thumbSrc" data-imagesrc="@imgSrcModal" alt="image not found" width="203" height="136" />
        </a>
        <div class="caption">
          <h3>Thumbnail label</h3>
          <p>...</p>
          <p><a href="#" class="btn btn-primary" role="button">Button</a>  <a href="#" class="btn btn-default" role="button">Button</a>
          </p>
        </div>
      </div>

    </li>
    }
  </ul>
  <div class="modal fade" id="imageModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
        </button>
        <a href="" data-toggle="modal" data-target="#myModal">
          <img id="modalPreview" alt="image not found" width="355" height="355" />
        </a>
      </div>
    </div>
  </div>
</div>

this snippet of js adds the new thumbnail when a user selects a new image and then appends it to a ul list.

var listItem = 
        "<li id=\"" + responseText.YogaSpaceImageId + "\" class=\"col-sm-6 col-md-4 imagethumbs\" data-yogaspaceid=" + $("#HiddenYogaSpaceId").val() + ">" +
            "<div class=\"thumbnail\">" +
            "<a id=\"" + responseText.YogaSpaceImageId + "\" class=\"close\" href=\"#\">×</a>" +
                "<a class=\"image\" id=\"" + imageId + "\" href=\"\" data-toggle=\"modal\" data-target=\"#myModal\">" +
                    "<img id=\"" + imagesourceId + "\" src=\"" + thumbSrc + "\" data-imagesrc=\"" + imgSrcModal + "\" alt=\"image not found\" width=\"203\" height=\"136\" />" +
                "</a>" +
                "<div class=\"caption\">" +
                    "<h3>Thumbnail label</h3>" +
                    "<p>...</p>" +
                    "<p><a href=\"#\" class=\"btn btn-primary\" role=\"button\">Button</a> <a href=\"#\" class=\"btn btn-default\" role=\"button\">Button</a></p>" +
                "</div>" +
            "</div>" +
        "</li>";

    var $li = $(listItem);
    $('ul#sortable').append($li);
chuckd
  • 13,460
  • 29
  • 152
  • 331
  • You either need to add the close event handler when you add the new element dynamically, or use a delegate (e.g., `$('.a_close_parent').on('click', '.close', func...)`). – Jared Farrish Mar 20 '15 at 22:22
  • can you provide a better example please!? – chuckd Mar 20 '15 at 22:36
  • This has been answered many, many (many) times. For example: http://stackoverflow.com/questions/9272438/jquery-click-event-not-firing-on-ajax-loaded-html-elements – Jared Farrish Mar 20 '15 at 22:38
  • I tried $("div.thumbnail").on("click", ".close", function (event) { var imageId = $(this).attr('id'); }); but had the same result – chuckd Mar 20 '15 at 22:41
  • Your code snippet doesn't do anything in the function body. – Jared Farrish Mar 20 '15 at 22:42
  • ya, I'm just trying to get the event to trigger first, before I add all the necessary code in the function. I also tried adding another class (.close.removethumb) because it looks like bootstrap has a close class, and the bootstrap modal is using it and there might be interference here. But .close.removethumb isn't working either – chuckd Mar 20 '15 at 22:44
  • Use `console.log('test');` in the function body with the Javascript console open so you can see it working. – Jared Farrish Mar 20 '15 at 22:45
  • I'm setting breakpoints so I know I'm not triggering the event – chuckd Mar 20 '15 at 22:46
  • This is a simplified example: http://jsfiddle.net/s89qdno4/ – Jared Farrish Mar 20 '15 at 22:53
  • Also, it appears that you're *adding* `div.thumbnail` when the `.close` is added, it needs to be a node that's a parent of `.imagethumbs` (or something that was present in the dom that's both a parent of where `div.thumbnail` will be appended and was present when the original event is added). That's how delegates work. The other option is add the jQuery event handler after the content is appended to the dom. What you're doing in the question, though, translates to *add this event handler to any matching elements*; what's missing is *now and in the future*. Delegates approximate that last part. – Jared Farrish Mar 20 '15 at 22:56
  • Here's the second (add the event handler with the element append) option: http://jsfiddle.net/s89qdno4/1/ – Jared Farrish Mar 20 '15 at 23:03
  • ah I see! I have to use a tag that was there before the new stuff is added. I tried $("ul#sortable").on("click", ".close.removethumb", function (event) { var imageId = $(this).attr('id'); }); and it's now triggering on the newly added stuff, but now the modal window is popping up everytime I remove the thumb – chuckd Mar 20 '15 at 23:32
  • You need to [stop propagation of further events](http://stackoverflow.com/a/1357151/451969). I usually use a `return false;` at the end of the event handler, which does both prevent default and stop propagation. – Jared Farrish Mar 20 '15 at 23:42
  • I tried both return false and event.preventDefault and the modal is still popping up. – chuckd Mar 20 '15 at 23:52
  • Use `event.stopPropagation()`. `event.preventDefault()` doesn't stop propagation; what it seems to be is that your modal is being triggered by the click in a containing element to the X button. Another option would be to use the element's click event instead of the inline attribute `data-modal` and check if the event has been stopped with [`event.isPropationStopped()`](https://api.jquery.com/event.isPropagationStopped/) – Jared Farrish Mar 21 '15 at 00:02
  • I figured it out. I had another click event tied to the same type of click event for the removal of the thumb. it was on a click event from a 'li' tag. I fixed. thanks for your help!!!! – chuckd Mar 21 '15 at 00:08

1 Answers1

0

$('a.close') selects currently available elements, if you add a new element you need to call your jQuery on it as well.

$(element).yourOriginalQuery
feildmaster
  • 114
  • 6