Maps Ylno
Maps Ylno

Reputation: 43

I want to append image using jQuery into div with preexisting images and order the images alphabetically

I have a div with a list of images showing in a slideshow.

HTML

<div id="slideshow">
<img  src="../../img/apple.jpg"   >
<img src="../../img/banana.jpg"  >
<img  src="../../img/bear.jpg"   >
<img src="../../img/raspberry.jpg"  >
<img  src="../../img/strawberry.jpg"   >
</div>

I have a JQuery function to dynamically add images to the slideshow

Javascript

$( "#slideshow" ).append('<img src="../../img/' + new_fruit_image + '">'); 

Is there a way to add the image into the div according to the name ? For example: I want to add mango.jpg into the 4th image position after bear.jpg and before raspberry.jpg .

Upvotes: 2

Views: 422

Answers (2)

Vinoth K
Vinoth K

Reputation: 106

Use the below code to add slider image. This code will insert the image into the div according to the name.

var new_fruit_image = 'mango.jpg';
var i=0;
var imgs = new Array();
$('#slideshow img').each(function(){
  var src = $(this).attr("src");
  imgs[i++] = src.match(/(\w*)\.\w{3,4}$/)[1];
});
var newImg = new_fruit_image.match(/(\w*)\.\w{3,4}$/)[1];
imgs[i] = newImg;
imgs.sort();
var insertPosition = $.inArray(newImg,imgs);
if(insertPosition!=0)
{
  $("div#slideshow img").eq(insertPosition-1).after($('<img src="../../img/' + new_fruit_image + '">'));
} else {
  $("div#slideshow img").eq(insertPosition).before($('<img src="../../img/' + new_fruit_image + '">'));
}

Upvotes: 1

T J
T J

Reputation: 43156

You could try something like this

function rearrange() {
 var elements = $('img');
 var images = elements.map(function () {
    var src = this.src;
    return src.substring((src.lastIndexOf('/') + 1), src.length);
 });
 images.sort();
 $.each(images, function (index, value) {
    $('#slideshow').append($('img[src*="' + value + '"]'));
 });
}

Demo

Upvotes: 0

Related Questions