0

Im having a brain fart at the moment, most likely due to being late at night. Any who, I have content that is prepended to the document after an ajax call. I am trying to assign a click event to these elements that are being prepended but it is not firing. Recreating the elements in static html fine.

Jquery

$('.row').click(function() {
    $(this).children('.slide2').stop().slideToggle(200);
})


$('<div class="row"><div class="main"><div class="split6">'
                         + data.some + '</div><div class="split6">' 
                         + data.some + '</div><div class="split6">' 
                         + data.some + '</div><div class="split6">'
                         + data.some + '</div><div class="split6">'
                         + data.some + '</div><div class="split6">'
                         + data.some + '</div></div><div class="slide2"><span>Info: '
                         + data.some + '</span><span>Info: '
                         + data.some + '</span><span>Info: '
                         + data.some + '</span></div></div>').prependTo('#results').hide().slideDown(500);
Ray
  • 894
  • 1
  • 6
  • 23

3 Answers3

1

Use

$('#results').on('click','.row', function() {
    $(this).children('.slide2').stop().slideToggle(200);
})

You need to use Event Delegation for dynamically create elemnts. You have to use .on() using delegated-events approach.

i.e.

$(document).on('event', 'selector', callback_function)

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

Satpal
  • 132,252
  • 13
  • 159
  • 168
0

You need to use event delegation since your .row has been added dynamically here:

$('body').on('click','.row', function() {
    $(this).children('.slide2').stop().slideToggle(200);
})

Event delegation will helps you to attach the click event to these newly created .row elements.

Felix
  • 37,892
  • 8
  • 43
  • 55
0

you should use delegate for that

$(document).on("click",".row",function(){
   $(this).children('.slide2').stop().slideToggle(200);
});

It helps you to attach handlers for the future elements

Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53