views:

41

answers:

1

The page section is:

<div id="cartslide">
    <div id="swrapper">
        content goes here
    </div>
</div>

jquery animate section:

$(document).ready(function () {

$('#animate-both').click(function () {
   $('#cartslide').animate({
       opacity: 'toggle',
       height: 'toggle'
    });
  });
});

So far, this works perfectly. The trouble arises when I replace contents of the "swrapper" section, with this:

           $.ajax({
                type: "POST",
                url: "cart/slider",
                data: dataString,
                cache: false,
                success: function(html){
                     $("#swrapper").replaceWith(html);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                     alert(errorThrown + ' '+ textStatus);
                }
           });

The content gets replaced (I can see it with firebug), but it will no longer toggle the contents of "cartslide", the enclosing div.

I'm surprised that this. I would think it would work, but it doesn't, I suppose because the contents of the inner div (swrapper) were replaced.

Is that the reason?

Is there a workaround?

Thanks!

+2  A: 

If #animate-both is in #swrapper, yes, there is a reason.

Events are attached to divisions when you attach them, meaning attaching once. If you replace it, the item that contained the event is no longer there.

The workaround is using jQuery's live function, meaning that even if one is created (which includes replacing), it will work:

$(document).ready(function () {

$('#animate-both').live( 'click', function () {
   $('#cartslide').animate({
       opacity: 'toggle',
       height: 'toggle'
    });
  });
});
Kerry
+1, very feasible.
Ryan Kinal