Kevin Jung
Kevin Jung

Reputation: 3103

on click randomize from xml with javascript

I am trying to create a xml based image display with a on click button.

so let say in my external xml file, i have the following:

<?xml version="1.0" encoding="utf-8"?>
<gallery>
    <photo name="summer">
        <file>imageone.jpg</file>
    </photo>
    <photo name="winter">
        <file>image2.jpg</file>
    </photo>
    <photo name="sprint">
        <file>3.jpg</file>
    </photo>
    <photo name="fall">
        <file>four.jpg</file>
    </photo>
</gallery>

On the webpage, I would like to have a button, when click it would shuffle from the above list and display one of the images randomly along with the corresponding photo name node.

I have looked into various jquery xml parsers but it i am having trouble randomizin it. is this possible to do?

Thanks!

Upvotes: 1

Views: 891

Answers (2)

DarthJDG
DarthJDG

Reputation: 16591

Just generate a random number after retrieving your photo array and pick one:

$photos = $(xmldata).find('photo');
$randomImage = $photos.eq(Math.floor(Math.random() * $photos.length));

$name = $randomImage.attr('name');
$img = $randomImage.find('file').text();

Upvotes: 2

Scherbius.com
Scherbius.com

Reputation: 3414

I would suggest to:

1) read all image names with any parser into array
2) randomize the array with jQuery
3) select and use 1

Upvotes: 0

Related Questions