1

This problem is bugging me out a bit. Should be a very simple solution but I can't quite grasp it. What I am doing is creating several nested elements via Jquery and then removing it from the page using JQuery.fade() method.

The close button on the element created does not fire the event but if applied to an independant button, it works.

Javascript:

$( document ).ready(function() {

$("button.create").click(function(){
  // action goes here!!
   // $(".alertBox").fadeIn();
    $('.alerts').append('<div class="alertBox"><span class="hide"><a href="#">X Close</a></span><p><strong>Alert!</strong> Thank you for submitting your comment. Scroll to the bottom of the page to view it.</p></div>');
    return false;
});

$("button.close").click(function(){
  // action goes here!!
    $(".alertBox").fadeOut();
    return false;
});

$(".hide").click(function(){
  // action goes here!!
    alert("check check");
    $(".alertBox").fadeOut();
});

});

HTML:

<h1>Fun with Alert Boxes</h1>
<p>This page is to test the ability to add or remove alert boxes from the DOM. By clicking on the button below, you will make an alert box appear and then you will be able to close the alert box with a button in the top right corner. This will all rely on JQuery to add and remove content from the DOM.<p>

<div class="alerts"></div>

<p>&nbsp;</p>    
<button class="create">Create Alert</button>
<button class="close">Destroy Alert</button>

And I have a Fiddle for it http://jsfiddle.net/coolwebs/5n5nosdc/4/ - I have checked it with Console log and can't see any obvious errors. Obviously the issue is that because the function is declared before the element is available on the page, is it possible that that is why it does not work?

Update: Did some testing by generating the script dynamically and it proved my suspicion.

Ryan Coolwebs
  • 1,523
  • 3
  • 20
  • 36
  • For dynamic click use `.on('click','selector',function())` http://jsfiddle.net/5n5nosdc/5/ – Satinder singh Jun 02 '15 at 06:28
  • 1
    If You want to trigger an event on dynamically added element to document - use delegated events - I've even wrote a blog post about it - feel free to take a look: http://lukaszkups.net/blog/0003_delegated_vs_direct_jquery_on_method/ – lukaszkups Jun 02 '15 at 06:36

2 Answers2

2

Use Event delegation for dynamically created elements

$('.alerts').on('click', '.hide', function(){
  // action goes here!!
    alert("check check");
    $(".alertBox").fadeOut();
});

For your reference study Event Delegation in SO

Community
  • 1
  • 1
Sudharsan S
  • 14,830
  • 3
  • 27
  • 47
1

Use event delegation for dynamically created events. Also I guess when you click the close button, you want to fadeOut that particular alertBox. Use this code.

$('.alerts').on('click', '.hide', function(){
  // action goes here!!
    alert("check check");
    $(this).closest('.alertBox').fadeOut(); //See this
});

Fiddle

Zee
  • 8,051
  • 5
  • 31
  • 58