jQuery: Insert HTML into a compressible division with .prepend () - how to use the click event on this HTML element?

advertisements

Following issue: I have a hidden div container called "#window-hidden". When a user clicks on a link the HTML of the linked document should be inserted into this div container by AJAX (working so far". This container should be draggable as well (working so far). But additionally I need a close-button to hide this div container again - and here appears the trouble.

My code:

$('.top_navigation .address a').click(function() {
  var myUrl = SOME CODE TO GET THE URL - WORKING;
  $('#window-hidden').load(myUrl, function() {
    var closer = '<div id="closer"><a href="#">X</a></div>';
    $(this).prepend(closer);
    $(this).fadeIn();
    });
  return false;
});

$('#window-hidden').draggable();

$('#closer a').on('click', function() {
  $('#window-hidden').fadeOut();

});

The first block of the code loads the HTML into the div container as well as it adds the "closer" element into the container. Everything is fine so far. The second block makes the container draggable. And with the last block of code I wanted to close the window again but it does not work. Maybe it is because the parent container (#window-hidden) is draggable? Or maybe it is because the element #closer is inserted after the DOM was built??

Best, Tobias


click events only work on elements that exist in the DOM on document ready. You need to use either on (if you're using jQuery 1.7+) or delegate (for earlier jQuery versions) to achieve what you need. Try either of these depending on your version:

on:

$("#window-hidden").on("click", "#closer a", function () {
    $('#window-hidden').fadeOut();
});

delegate:

$("#window-hidden").delegate("#closer a", "click", function () {
    $('#window-hidden').fadeOut();
});