Reputation: 530
I am really struggling with this for a while so i guessed maybe SO knows the solution.
I created a live search which (after you searched for a product id) shows up a row with... a product like so (simplified):
<div id="78524" class="live_search_product">
<!-- productinformation here -->
</div>
Underneath this there is a product list which has products in it. These products are alphanumerically sorted like this:
<div class="products_wrapper">
<div id="78500">
<!-- productinformation here -->
</div>
<div id="78501">
<!-- productinformation here -->
</div>
(id 78524 should come here when clicked)
<div id="78526">
<!-- productinformation here -->
</div>
</div>
What i want:
When you click on the .live_search_product
product it needs to put itself 'between' the correct id's ascending, i can't figure this out and i don't see the logic behind this.
Can you guys give me a push in the right direction?
Thanks a lot!
Upvotes: 0
Views: 41
Reputation: 8515
You could get a list of IDs, sort it and then determine at which index the new element should be placed and insert it after element on index - 1
:
const $list = $('#product-list');
$('.live_search_product').on('click', function() {
const $this = $(this);
const thisId = +$this.attr('id');
const ids = [];
$list.find('div').each(function() {
ids.push(+$(this).attr('id'));
});
ids.push(thisId);
ids.sort(function(a, b) { return a - b; });
const index = ids.findIndex(function(el) { return el === thisId; });
$this.insertAfter($list.find('div').eq(index - 1));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="78524" class="live_search_product">
Product 78524 info product info product info [click me]
</div>
List:
<div id="product-list">
<div id="78500">
Product 78500 info product info product info
</div>
<div id="78501">
Product 78501 info product info product info
</div>
(id 78524 should come here when clicked)
<div id="78526">
Product 78526 info product info product info
</div>
</div>
Upvotes: 1