2

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 .

Joseph B
  • 5,519
  • 1
  • 15
  • 19
Maps Ylno
  • 33
  • 6
  • It would be easier to append the image to the end of the `div` and then sort them all. – Rory McCrossan Jul 08 '14 at 09:26
  • This article might help: http://stackoverflow.com/questions/6076820/how-to-order-dynamically-created-elements-based-on-a-custom-attribute – Fabian de Pabian Jul 08 '14 at 09:34
  • var lstImages=$("#divID img"); It contains array of all images clear the div and recreate the all image at any position – Sagar Chavan Jul 08 '14 at 09:40
  • I think that the way you are looking is something like this: 1- Get all the img tags into that div. 2- Iterate all of them and get the src attribute. 3- When the name of src suits you, use the after or before command to append you new image. – fray88 Jul 08 '14 at 09:42
  • Yes, that would work! Maybe I didn't explain properly. It should be inserted automatically! Suppose a user want to insert a new file, it will depend on the name, which I don't know before. @kamesh – Maps Ylno Jul 08 '14 at 09:44
  • @MapsYlno ya thats my mistake. I didnt see 'alphabetically' this word.. so i deleted the code – kamesh Jul 08 '14 at 09:52

2 Answers2

1

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 + '">'));
}
Vinoth K
  • 106
  • 3
0

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

T J
  • 42,762
  • 13
  • 83
  • 138