Caylean
Caylean

Reputation: 197

Non Javascript alternative for rotate on pageload script

I have here a Site where i wish to create a Gallery with 16*3 set of images.

For wach Set i have right now a script that randomly changes the image with each load of the page:

<script type="text/javascript">
images = new Array(3);
images[0] = "<a href='http://www.domain.tld/'><img border='0' src='./images/first.jpg' width='239' height='320' class='kontimg' /></a>";
images[1] = "<a href='http://www.domain.tld/'><img border='0' src='./images/second.jpg' width='239' height='320' class='kontimg' /></a>";
images[2] = "<a href='http://www.domain.tld/'><img border='0' src='./images/third.jpg' width='239' height='320' class='kontimg' /></a>";
index = Math.floor(Math.random() * images.length);
document.write(images[index]);
</script>

All in all pretty basic, but the users with disabled JS are getting more, not less, so i need a different alternativeand also this bloats the Code really badly. Imagine that I have used That snippet 16 times on one page.

I tried to find something that could be done with this jquery stuff, but mostly that are slideshows and other rotating things (quite amazing stuff) but i couldn't find a single "on pageload, load random image" code.

I even tried already a slideshow to go with that, but for some reason it doesn't work without messing up the complete css again. Mostly the images were in a ul/li-Tag, but when i added the jquery files and hooks inside the page, it never worked.

Is there any other solution than that? Of should i just keep my bloated js and add a are where i just load the first 16 mages and go with that?

Would be really happy if someone could lend me a hand here.

Kind regards Sascha

Upvotes: 1

Views: 69

Answers (1)

Jack Guy
Jack Guy

Reputation: 8523

There's no way to do this without JavaScript. If you're just looking to avoid a little repetition, assuming you're using jQuery you could do something like this:

var imageNames = ['first', 'second', 'third'];
var image = imageNames[getRandomInt( 0, imageNames.length - 1 )]

$("body").append("<a href='http://www.domain.tld/'><img border='0' src='./images/"+image+".jpg' width='239' height='320' class='kontimg' /></a>");

function getRandomInt(min, max) {
   return Math.floor(Math.random() * (max - min + 1)) + min;
}

Upvotes: 1

Related Questions