0

I have tried moving last element in my list to first position on click, but it does not work. I did it according to answer from this question: Move last child to first position . Firebug shows me that something happens with the list, but it's certainly not last to first change :(

jQuery:

$(document).ready(function(){   
    $(".carousel-button-left").click(function(){
    var $ul=$(this).next();                 
    var $lastchild=$ul.children().last();
    $ul.prepend($lastchild);
    });
});

HTML:

<div class="testowyDiv">
    <img class="carousel-button-left" src="ikony/strzalkal.png">
    <div class="testowyDiv2">
        <ul class="testowyUl">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            <li>6</li>
            <li>7</li>
            <li>8</li>
            <li>9</li>
        </ul>
    </div>
    <img class="carousel-button-right" src="ikony/strzalkap.png">
</div>
Community
  • 1
  • 1
Xyzk
  • 1,332
  • 2
  • 21
  • 36

3 Answers3

4
$(document).ready(function(){   
    $(".carousel-button-left").click(function(){
    var $ul=$(this).next().find(".testowyUl");   // by next we reach on next div then by find we reach on ul               
    var $lastchild=$ul.children().last();
    $ul.prepend($lastchild);
    });
});
Rituraj ratan
  • 10,260
  • 8
  • 34
  • 55
  • 1
    one note: I recommend using `.closest(sth).find(sth)` over `.next(sth).find(sth)`. What if you place an element between the ul and its corresponding button? – John Dvorak Sep 02 '13 at 06:13
  • we use closest to go on parent level when we talk sibling , next, prev the use next,pre and sibling method in jquery and i accept it by these we depends on dom by closest we go on directly but here i think next is great any way your suggestion always welcome thanks @JanDvorak – Rituraj ratan Sep 02 '13 at 06:19
0
$(document).ready(function(){   
    $(".carousel-button-left").click(function(){
    var $ul=$(".testowyUl");  //do you need node traversing, if not use direct, better keep a id for it 
    var lastchild=$ul.children().last();
        console.log(lastchild.val());
    $ul.prepend(lastchild);
    });
});

Demo -Fiddle

metalfight - user868766
  • 2,722
  • 1
  • 16
  • 20
-1

Using prepend or insertBefore.

Sample:

$(document).ready(function(){   
    $('.carousel-button-left').click(function() {
        var first = $('.testowyUl li:first');
        var last = $('.testowyUl li:last');
        last.insertBefore(first);
    });
});
long.luc
  • 1,191
  • 1
  • 10
  • 30