caramba
caramba

Reputation: 22490

Clone and insertAfter only once

I want to clone the first-child button from #navCotainer and insert it after the last button.

Now the Problem is: The script kind of inserts the first child 3 times. what do I have to do to get ir right? And also, what am I doing wrong?

of course a link to the fiddle http://jsfiddle.net/ygjDR/ and the code:

 <script src="http://code.jquery.com/jquery-1.9.1.js"></script>

<span class="moveNav8 left8">left</span>

<div id="navContainer" style="width: 100%; overflow-y: auto;">
    <div class="button">1</div>
    <div class="button">2</div>
    <div class="button">3</div>
    <div class="button">4</div>
</div>

<script type="text/javascript">
    $(document).on('click','.moveNav8', function() {
        if($(this).hasClass('left8')) {
            $('.button').animate({
                left: '-=305'
            }, 1000, function() {
                $('#navContainer div.button:first-child').addClass("xxxx");
                $('#navContainer ').children('div.button:first-child').clone().css("background-color","orange").insertAfter("#navContainer div.button:last-child");
            });
        }
    });
</script>

<style type="text/css">
.button {
    position: relative; float: left;
    width:100px;
    height:50px;
    background-color:green;
    margin-right:10px;
}
.moveNav8 {
    position:absolute;
    top:100px;
    left:0px;
    background-color:red;
    width:40px;
    height:40px;
}
.moveNav8.right8 {
    left:100px;
}
</style>

Upvotes: 2

Views: 972

Answers (2)

dfsq
dfsq

Reputation: 193311

Animation callback is invoked for every item, appending a button 4 times. Instead execute callback only once after the last animation using deferred pattern:

$(document).on('click', '.moveNav8', function () {
    if ($(this).hasClass('left8')) {
        $('.button').animate({
            left: '-=305'
        }, 1000).promise().done(function () {
            $('#navContainer div.button:first-child').addClass("xxxx");
            $('#navContainer').children('div.button:first-child').clone().css("background-color", "orange").insertAfter("#navContainer div.button:last-child");
        })
    }
});

http://jsfiddle.net/ygjDR/3/

Upvotes: 1

dav
dav

Reputation: 1219

Try this:

http://jsfiddle.net/gtttG/

You need to add a check for $(".button:animated").length === 0.

Upvotes: 2

Related Questions