5

I'm trying to add a Class to an existing div container and insert a new div (on success) below the existing one.

<script>
$(document).ready(function(){
  $(".entry").click(function(){
     $('#content').addClass("col2",1000).after('<div class="box col2">test</div>', function(){
        $(this).slideDown();
     });
  });
});
<script>

Unfortunately this code doesn't work correctly. The slideDown function doesn't work and the new div does already appear even if the previous function hasn't already finished.

Would be nice if someone could help me.

Mohammad
  • 21,175
  • 15
  • 55
  • 84
damian
  • 5,314
  • 5
  • 34
  • 63

3 Answers3

4

Your closing tag should be </script>

Also, the effect that you want may be the folowing:

$(".entry").click(function() {
    $('#content').addClass("col2").after('<div class="box col2">test</div>');
    $('.box:last').hide().show(300);
});

Fiddle here


Edit: Based on you comment, I guess that maybe you want this:

$(".entry").click(function() {
    $('#content').addClass("col2");
    setTimeout(function() {
        $('#content').after('<div class="box col2">test</div>');
        $('.box:last').hide().show(300);
    }, 500);
});

Fiddle here

Benjamin Crouzier
  • 40,265
  • 44
  • 171
  • 236
1

after() doesn't take a callback.

Instead, you need to create a new jQuery object for the new element, call slideDown() on it, and pass it to after().
For example:

$(...).after(
     $('<div class="box col2">test</div>').slideDown()
);

Obviously, this will only work for elements that slideDown() actually works on.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Didn't know that after() doesn't take a callback. Thank you. I changed the code but the slideDown still doesn't work. – damian Oct 11 '11 at 22:24
  • @PhillyNJ: This should work fine. What problem are you having? – SLaks May 11 '15 at 16:01
  • @SLaks Doesn't work for `tr`, which is out of scope now that I know tr doesn't support this. I can't up vote until you edit your answer. – PhillyNJ May 11 '15 at 16:16
  • @PhillyNJ: Edited. See http://blog.slaks.net/2010/12/animating-table-rows-with-jquery.html – SLaks May 11 '15 at 16:17
0
$(document).ready(function(){
  $(".entry").click(function(){
     $('#content').addClass("col2").after('<div class="box col2">test</div>').slideDown();
  });
});

This should do the trick. .addClass() only takes one input and .after() does not accept a callback function. However with the above example the class will be added and the html will be appended before the .slideDown() function is called.

Some Documentation Links:

Jasper
  • 75,717
  • 14
  • 151
  • 146
  • I tried your code but it still doesn't work correctly. The slideDown doesn't go well and the div with class box col2 appears to early. Do you know how to solve that? – damian Oct 11 '11 at 22:27
  • By the way addClass does takte 2 inputs (combined with the jquery UI) http://docs.jquery.com/UI/Effects/addClass – damian Oct 11 '11 at 22:29