0

Hi I am creating a new element and child of that element with beforesend in Ajax.

Later on I want to show the child element if I click on its parent...

$('#submit-task').on('click', function() {
    // variable declarations etc
    jQuery.ajax({
        // other data
        beforeSend: function() {
            jQuery('#' + month + ' .month-tasks-design').append(
                '<div class="month-task" data-id="' + next_id + '" style="width:0%;background: ' + colour + ';"><div class="task-info">Name: ' + name + '<br />Design Hours: ' + design_hours + '<br />Description: ' + description + '<br /></div></div>');

            jQuery('#' + month + ' .month-tasks-dev').append(
                '<div class="month-task" data-id="' + next_id + '" style="width:0%;background: ' + colour + ';"><div class="task-info">Name: ' + name + '<br />Development Hours: ' + dev_hours + '<br />Description: ' + description + '<br /></div></div>');

            jQuery('.month-tasks-design div[data-id=' + next_id + ']').animate({ width: design_width + '%'}, 1000,  function() {});

            jQuery('.month-tasks-dev div[data-id=' + next_id + ']').animate({ width: dev_width + '%'}, 1000,  function() {});               


        },
        // other data

    }); 
});

$('.month-task').on('click', function(e) {
    if ( e.target !== this ) { return; }
    var task_info = $(this).find('.task-info');
    $(task_info).fadeIn(200);
});

however nothing happens when I click on .month-task, it does work however with page loaded html, just not with the newly generated html

Adrian
  • 1,976
  • 5
  • 41
  • 105

2 Answers2

0

Try to use event-delegation at this context,

$(document).on('click','.month-task', function(e) {
    if ( e.target !== this ) { return; }
    var task_info = $(this).find('.task-info');
    $(task_info).fadeIn(200);
});

Note : In the place of document, you should use a static parent to the appended element.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • 1
    Thank you that worked, I will accept answer in 10 mins – Adrian Aug 18 '14 at 10:43
  • Just wondering what the difference between that and what I originally had is? – Adrian Aug 18 '14 at 10:44
  • I mean in terms of why one works and the other doesnt – Adrian Aug 18 '14 at 10:44
  • 1
    @Adrian While registering event, the element belongs to that selector would not be available in the dom. since you are appending it on the runtime. so at this context we have to use event-delegation. Event-delegion internally uses event bubbling to overcome the issue. please read [here](http://learn.jquery.com/events/event-delegation/) to know more about it. – Rajaprabhu Aravindasamy Aug 18 '14 at 10:46
0

That is not the way to delegate , say like bellow

$(document).on('click', '.month-task', function(e) {
Mritunjay
  • 25,338
  • 7
  • 55
  • 68