Like _prevent_ divs from randomly appearing

Ok, so I am learning front-end dev with javascript / jquery / bootstrap via FreeCodeCamp. This is not the main part of the project, but I don’t understand it, and it distracts me too much. In this code here: http://codepen.io/JDenman6/pen/zqeGwp/ - I have an array of Twitch.tv usernames that I look through the API and create divs to display based on the JSON object that comes back from the call API

The strange thing is that every time I refresh the page, I get divs in a different (apparently random) order. I assume that the API calls exit asynchronously and the divs are displayed in the order that the API ends.

When I Googled for other people having problems with divs in random order, I found many solutions causing random display order but nothing disturbed it. So, I went looking for a solution to sort the div and found this post Ordering a DIV based on the class name using Javascript / Jquery , which led me to this piece of code:

$(function(){ var elem = $('#twitcherList').find('div').sort(sortMe); $('#twitcherList').append(elem); }); function sortMe(a, b) { return a.className < b.className; } 

Only I could not get it to work. I dropped my source code to have a look here: http://codepen.io/JDenman6/pen/MeYOJP .

The list of divs in twitcherList on the html tab is a check for the twitcherList after rendering the source code. I thought it would be easier to sort them if they were hard-coded rather than coming from an API call. I also added a small test div and pasted some code into the sort function to 1) verify that it is running, and 2) double check that the a.classname and b.class names returned what I thought they were. p>

I feel that I am missing something huge, fundamental, and perhaps quite obvious. Any thoughts?

0
source share
1 answer

You need to return -1 , 0 or 1 based on the correct sort condition.

 function sortMe(a, b) { return a.className.localeCompare(b.className); } 

For better browser support, use

 function sortMe(a, b) { return a.className < b.className ? 1 : -1; } 
0
source

Source: https://habr.com/ru/post/1485360/


All Articles