RedGiant
RedGiant

Reputation: 4748

Trying to use different array data structure in a jQuery script

I came across this random image rotator

var theImages = new Array() 
    theImages[0] = 'img1"'  theImages[1] = 'img2"'......   
var shuffled = [];    
while (theImages.length) {
    shuffled.push(theImages.splice(Math.random() * theImages.length, 1));
}            
$(document).ready(function(){        
    //Runs Script each time there is an <li>
    $("#news li").each(function(index){                
        //Puts Image in front of everything in <li>
        $(this).prepend('<img src="'+shuffled[index]+'">');            
    });

});

And I integrated it into a jQuery Carousel. You can see (my fiddle) here. The problem is that the array structure I want to use for the Carousel is different from the rotator's. The rotator uses:

var theImages = new Array() 
theImages[0] = 'img1"'
theImages[1] = 'img2"'
theImages[2] = 'img3"'

But I want to use the following for the Carousel because I want to input a link to each picture as well.

var theImages = [
['img1','url_1'],
['img2','url_2'],
['img3','url_3']];

The outcome I'm looking for would be like:

<div id="carousel1"> 
<div class="1"><a href="url_1"><img src="img1"></a></div>
<div class="1"><a href="url_2"><img src="img2"></a></div>......

From what I've read, I have to use for in loop to assign the data and can't simply use what the image rotator is using:

$("#carousel1 .1").each(function(index){    

$(this).prepend('<a href="'+imgPath+''+shuffled[index]+'"><img 
src="'+urlPath+''+shuffled[?url](?url)+'"></a>');

Is that true? Is there any way that allows me to populate the images as well as the urls in the Carousel?

Upvotes: 0

Views: 69

Answers (3)

Felix Kling
Felix Kling

Reputation: 816272

No, never use for ... in for arrays. All you have to do is change

'<img src="'+shuffled[index]+'">'

to

'<a href="'+imgPath+shuffled[index][1]+'"><img src="'+urlPath+shuffled[index][0]+'"></a>'

since the image path is the first element of the inner array, and the link is the second one.

See Access / process (nested) objects, arrays or JSON for more info.

(I assume imgPath and urlPath are actually defined somewhere and contain URLs. If not, you should remove them.)

Upvotes: 2

EdL
EdL

Reputation: 435

for(var i=0;i<theImages.length;i++){
    newTheImagesArray.push([theImages[i],theImages[i]])
}

This should work for what you want

Upvotes: 0

Tim B
Tim B

Reputation: 41168

Your problem is that your source array (the shuffled values) only contains one value but the final resulting one you want to have pairs of values. That extra data needs to come from somewhere, the computer can't just invent it.

The easiest way to do this is to modify the shuffle code and instead of shuffling single strings shuffle pairs of strings instead.

i.e. something like

var theImages = new Array() 
theImages[0] = ['img1"', data1]
theImages[1] = ['img2"', data2]

Upvotes: 1

Related Questions