Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Perform callback after append

I am appending content to a list using:

  $('a.ui-icon-cart').click(function(){          $(this).closest('li').clone().appendTo('#cart ul');   }); 

I want to perform further functions to the appended content (change class, apply animations etc)

How can I perform a callback on this function that will allow me to perform functions on the appended data?

like image 594
user342391 Avatar asked Jun 24 '10 21:06

user342391


People also ask

How to appendChild in jQuery?

jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.

How to add after in jQuery?

jQuery insertAfter() MethodThe insertAfter() method inserts HTML elements after the selected elements. Tip: To insert HTML elements before the selected elements, use the insertBefore() method.

Which jQuery will you use if there is a need to insert specified content after a selected element?

jQuery after() Method The after() method inserts specified content after the selected elements.


2 Answers

jQuery's .each() takes a callback function and applies it to each element in the jQuery object.

Imagine something like this:

$('a.ui-icon-cart').click(function(){   $(this).closest('li').clone().appendTo('#cart ul').each(function() {     $(this).find('h5').remove();      $(this).find('img').css({'height':'40px', 'width':'40px'});     $(this).find('li').css({'height':'60px', 'width':'40px'});   }); }); 

You could also just store the result and work on it instead:

$('a.ui-icon-cart').click(function(){   var $new = $(this).closest('li').clone().appendTo('#cart ul')   $new.find('h5').remove();    $new.find('img').css({'height':'40px', 'width':'40px'});   $new.find('li').css({'height':'60px', 'width':'40px'}); }); 

I would also suggest that instead of mofiying the CSS like that you just add a class to your cloned li like this:

$(this).closest('li').clone().addClass("new-item").appendTo('#cart ul'); 

Then setup some styles like:

.new-item img, .new-item li { height: 40px; width: 40px; } .new-item h5 { display: none } 
like image 112
gnarf Avatar answered Sep 19 '22 17:09

gnarf


Unfortunatly adding callbacks to dom operations is not something that can be done in a neat fashion using javascript. For this reason it is not in the jQuery library. A settimeout with the timer "1ms" however always puts the function in the settimeout on the bottom of the call stack. This does work! The underscore.js library uses this technique in _.defer, which does exactly what you want.

$('a.ui-icon-cart').click(function(){     $(this).closest('li').clone().appendTo('#cart ul');     setTimeout(function() {         // The LI is now appended to #cart UL and you can mess around with it.     }, 1); }); 
like image 27
douwe Avatar answered Sep 18 '22 17:09

douwe