Sort List of items by date data attribute

by thomas_david88

HTML

<!--

In your web app list layout you can use the following markup:

<li class="sort-item" data-event-date="{tag_event date}">
    YOUR OTHER WEB APP TAGS HERE
</li>

This will work with your custom event date if your field is called "Event Date".  If it has a different name, just insert your custom tag in the "data-event-date" attribute.

-->


<ul class="sort-list">
    <li class="sort-item" data-event-date="2019-06-30 22:00">3</li>
    <li class="sort-item" data-event-date="2018-06-29 21:00">2</li>
    <li class="sort-item" data-event-date="2018-06-27 22:00">1</li>
    <li class="sort-item" data-event-date="2018-07-01 22:00">4</li>
    <li class="sort-item" data-event-date="2019-07-02 22:00">5</li>

</ul>

<button onclick="chat_order()">
test
</button>

JavaScript

function chat_order() {
    var container = $(".sort-list");
    var items = $(".sort-item");
    
    items.each(function() {
       // Convert the string in 'data-event-date' attribute to a more
       // standardized date format
       var BCDate = $(this).attr("data-event-date");
       /*console.log(BCDate);
       var standardDate = BCDate[1]+" "+BCDate[0]+" "+BCDate[2];*/
       var standartDate = new Date(BCDate).getTime();
       $(this).attr("data-event-date", standartDate);
 				console.log(standartDate);
    });
    

    items.sort(function(a,b){
        a = parseFloat($(a).attr("data-event-date"));
        b = parseFloat($(b).attr("data-event-date"));
        return a>b ? -1 : a<b ? 1 : 0;
    }).each(function(){
        container.prepend(this);
    });

}

/* This script sorts your list in descending order... to change it to ascending order change the "less than" operator (<) to "greater than" (>) */