All Collections
Technical documentation
Sort Translated Elements Alphabetically
Sort Translated Elements Alphabetically
Ishai Jaffe avatar
Written by Ishai Jaffe
Updated over a week ago

Sometimes in your website you have elements which are sorted alphabetically. After translating these elements you'll find out they are no longer sorted in the new language.
Bablic will not sort elements automatically, so not to brake the website functionality, but you can do that easily using Bablic JS API.

In this example we are sorting a select box with an id sortedSelectBox using Bablic JS API & jQuery.

This is the example select box:

<select id="sortedSelectBox">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>


And this is the example script to make sure it's always sorted. The script must be run after the element is created, run this code in the page head before the page is loaded will not work.

function sortTextElementsAfterTranslation(){            
      var selectElement = $(this);
      bablic.watch(selectElement.get(0),function(){
           // get all inner children, you can replace 'option' with
           // the child selector of your list items
           var items = $('option',selectElement);
           // remove items from list, without losing their data
           items.detach();
           // sort items by their new text value
           items.sort(function(a,b) {
               var firstText = $(a).text().trim().toLowerCase();
               var secondText = $(b).text().trim().toLowerCase();
               return firstText.localeCompare(secondText);
           });
           // add child elements to list
           selectElement.append(items);
      });
}
$('#sortedSelectBox').each(sortTextElementsAfterTranslation); 

Did this answer your question?