[Answer]-JQuery 1.11.3: Insert a div of "Tasks" based on the order of their categories

1๐Ÿ‘

โœ…

You can sort the categories you already have and then use a $insertAfter or $prepend in case of the first sorted category.

Take a look on this working example based on the code you gave:
https://jsfiddle.net/e6g4fu84/

// ADDING A NEW TASK IN A NEW CATEGORY

    categoryOfTask = "baa";

    newtask = document.createElement("task");
    $(newtask).html('<div><input type="checkbox"/><label>task foo inserted</label></div>');


// When you gonna add your new category holder add it like this:
    if ($("#category__" + categoryOfTask).length == 0){


  //Create your new Div just like you have done  
      if ($("#category__").length == 0)
         var newDiv = $("<div id=\"category__" + categoryOfTask + "\"><span>" + categoryOfTask + "</span></div>");
      else
         var newDiv = $("<br/><div id=\"category__" + categoryOfTask + "\"><span>" + categoryOfTask + "</span></div>");


   //But the trick happens when you will add your new category holder
   //----------------------------------------------------------


   //find all elements that have #category__X as id
        categoriesElements = $("#listOfThingsToDo div[id*=category__]");


   //And then add them on an array
        categoriesNames = [];
        $.each(categoriesElements, function(i, category){
            categoriesNames.push($(category).attr("id").split("__")[1]);
        });


    //Add your new category to the group and sort

        categoriesNames.push(categoryOfTask);
        categoriesNames.sort();


    //find where you should fit
        putCategoryAfter = categoriesNames.indexOf(categoryOfTask) - 1;


    //Then add it where it should be
        if(putCategoryAfter == -1) //If it's the first of the list
            $("#listOfThingsToDo").prepend(newDiv);    
        else{ //If it isn't the first find where it should be and insert it there
           $(newDiv).insertAfter("#category__"+categoriesNames[putCategoryAfter]);
        }

       newDiv.show();
}


// And after all add your task to it
    $("#category__" + categoryOfTask).append(newtask);

I comment the steps to clarify, hope i could help.
If this is what you are expecting just let me know. Best regards! ๐Ÿ™‚

๐Ÿ‘คGabriel Age

Leave a comment