javascript - Sorting elements in array -


i have array containing list of images have stored online:

var imgs = ["img1","img2","img3"...]; 

they displayed such:

var child, i; (i = 0; < imgs.length; i++) {     child.style.backgroundimage = 'url(https://mywebsite/images/' + imgs[i] + '.jpg)';     $('body').append(child); } 

however, i'm looking try display images based on attribute, can change depending on user action.

this attribute this:

child.setattribute("class", 0); 

say example, user decides click on image, attribute of image clicked on increment. class no longer '0' '1'. , because of so, image placed before others in array.

assuming 'img2' clicked, array like:

imgs = ["img2","img1","img3"...]; 

i feel method i'm going inefficient , have considered using objects or 2d arrays, i'm not sure start , lack experience. however, if isn't "such bad way" started, i'd appreciate if showed me how move elements in array.

thanks in advance.

you can try this:

$('body').find("img").on("click", function()  {     $(this).data("count", (number($(this).data("count")) + 1));       reorderimages(); });  function reorderimages() {     var imgs = $('body').find("img");      (var = 0; < imgs.length; i++)     {         var img1 = $(imgs[i]);         var img2 = (imgs.length > (i + 1) ? $(imgs[(i + 1)]) : false);          if (img2 && number(img1.data("count")) < number(img2.data("count")))         {             img1.before(img2);         }     } }; 

fiddle. here i'm using data attributes instead of class attribute, isn't designed case. swaps elements before() method.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -