Acoustic77 Acoustic77 - 4 months ago 9
jQuery Question

Reorganizing divs vertically with jquery

I have 5 divs going vertically down a page.

I want to be able to click any one, and have it move to be the first div in the order, the top of the "list" in a way. In a perfect world, the others would dim/decrease opacity and the clicked one would slide/animate up to the top while the others bumped down. But, that can come later. I've seen div-reordering done with CSS, but that's not continuously dynamic on the page.

I tried putting all 5 divs inside a container wrapper and doing this in css:

#wrapper { display: table; }


with this javascript (example for clicking second div):

$('#secondDiv').css("display","table-header-group");
$('#firstDiv').css("display","table-row-group");
$('#thirdDiv').css("display","table-row-group");
$('#fourthDiv').css("display","table-row-group");
$('#fifthDiv').css("display","table-row-group");


but that messed up my rounded corners on the div, my alignment, and other parts of my existing css.

This seems like it shouldn't be that hard, but I can't figure it out. Thanks for any help!

Answer

A very simple solution: move the element to the top using jQuery's prepend() to the parent element.

$("div").click(function() {    
    $(this).parent().prepend($(this));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Div1</div>
<div>Div2</div>
<div>Div3</div>
<div>Div4</div>
<div>Div5</div>
<div>Div6</div>
<div>Div7</div>
<div>Div8</div>
<div>Div9</div>
<div>Div10</div>

Comments