Lee Buckle
Lee Buckle

Reputation: 749

Rearrange the order HTML elements appear in with JavaScript or jQuery

I'm building a modular building program and have a side panel where the user can add the code of a module in order to make it appear in the list.

The list is simply span tags with text in. Since they are already in a set order in the HTML, they appear in that default order when they are made visible, rather than appearing at the bottom of the list each time a new one is made visible.

My workaround is to make all of the spans positioned absolute and use some jQuery/JS to do some calculations and move the latest visible-made span to the bottom.

This code works in moving the input field and button to the bottom of the list:

var searchModule = 0;
$("#add_module_button").click(function(){
   searchModule = "#" + document.getElementById("add_module_input").value;
   $(searchModule).css('display', 'block');
   visibleModules = $('.side_module:visible').length * 50 + "px";
   $('#add_a_module').css('top', visibleModules);
});

Is there a better solution out there for re-arranging HTML elements without essentially faking it with absolute positioning?

Upvotes: 1

Views: 3007

Answers (1)

Flyer53
Flyer53

Reputation: 764

If I get you right it's actually quite easy. Make use of jQuery.append(). If you use jQuery.append() to append an item to the same container it's already contained in, the item is actually removed from its current location and appended at the end. As far as I read your question that's what you want. The example below shows the basic idea ...

$('#container').append($('#three').css('display', 'block'));
$('#container').append($('#one').css('display', 'block'));
$('#container').append($('#five').css('display', 'block'));
.item{
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div class="item" id="one">One</div>
  <div class="item" id="two">Two</div>
  <div class="item" id="three">Three</div>
  <div class="item" id="four">Four</div>
  <div class="item" id="five">Five</div>
</div>

Upvotes: 1

Related Questions