Jump to content

Image Change


Chikwado

Recommended Posts

If you want to cycle through them you'll need to save the index as a cookie or in local storage. Even with a random selection you may want to save the old index just to prevent repeats. Here is a simple random approach...

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
<style>
#myImg{width:200px}
</style>
</head>

<body>

<img src="#" id="myImg" alt="no image found"/>

<script>
'use strict';
var phot = [];
phot[0] = 'path0.jpg';
phot[1] = 'path1.jpg';
/* ... */
phot[9] = 'path9.jpg';
var i = Math.floor(10*Math.random()); /* random 0 - 9 */
document.getElementById("myImg").src = phot[i];
</script>
</body>
</html>
Link to comment
Share on other sites

Yes! The code above works perfectly, But is it possible to store more than 10 image? I have heared a story that javascript does not read 1 and 0 as 10, instead it understand 1 as 1 and 0 as 0?

Edited by Chikwado
Link to comment
Share on other sites

You also could try this...

<script>
'use strict';
var phot = [
'path0.jpg',
'path1.jpg',
'path2.jpg',
'path3.jpg',
'path4.jpg',
'path5.jpg'];
var i = Math.floor(phot.length*Math.random());
document.getElementById("myImg").src = phot[i];
</script>
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...