Forum Moderators: open

Message Too Old, No Replies

Displaying pictures in an array

How do I put pictures in an array and then display them on the screen?

         

Adam5000

6:58 pm on Jun 17, 2007 (gmt 0)

10+ Year Member



I'm trying to put photos into an array and then display the first one on the screen. The code below recognizes the items in the array as text and writes "000.jpg" on the screen. But I'd like to display the 000.jpg photo on the screen instead of the name. Help!

<html>
<head>
<title>Slide show 004</title>

<script type="text/Javascript">

var photos= new Array()

photos[0]= "000.jpg"
photos[1]= "001.jpg"

var index =0;

document.write (photos[index]);

</script>

</head>
</html>

colandy

8:35 pm on Jun 17, 2007 (gmt 0)

10+ Year Member



Try this.
<SCRIPT type="text/javascript">

var photos = new Array("000.jpg","001.jpg");

var idx=0;

function showImage(index)
{
var mimg=document.getElementById('test');
mimg.setAttribute('src',photos[index]);
}

function initialise()
{
showImage(idx);
}

window.onload=initialise;
</SCRIPT>
<body>

<img id="test">

Whenever u want to change the image, call showImage with a different number.

Adam5000

12:19 am on Jun 18, 2007 (gmt 0)

10+ Year Member



That's works great Andy. You're brilliant. Now, can you fix it so the idx number increases by one each second, and then at the end, goes back to the first one and starts again in a loop, to create a slide show?

Logician

1:41 am on Jun 18, 2007 (gmt 0)

10+ Year Member



This should do it. Now all you have to do is explain it to your teacher.

<img id='test' src='000.jpg'>

<script type='text/javascript'>

SlideShow=
{
 pics:[], timer:null, holder:null, posn:0,

 init:function()
 {
  this.holder=document.getElementById(arguments[0]);

  for(var i=0, j=2; j<arguments.length; i++, j++)
   this.pics[i]=arguments[j];

  this.holder.src=this.pics[this.posn];

  this.timer=setInterval('SlideShow.swap()', arguments[1]*1000); 
 },

 swap:function()
 {
  if(++this.posn==this.pics.length)
   this.posn=0;
  this.holder.src=this.pics[this.posn];
 }
}

SlideShow.init('test', 1, '000.jpg', '001.jpg'); //<- add as many more images as desired

</script>

Adam5000

2:25 am on Jun 18, 2007 (gmt 0)

10+ Year Member



Thank you Logic. That works great. And I never thought of a student coming here to get help with his / her homework. I graduated about ten years ago but unfortunately I didn't take any Javascript classes.

What I'm doing is building my own personal website. And this slideshow is part of it. And I can see where what I'm trying to do would sound wacky enough to be a strange homework assignment.

In the end I'm going to vary the length of time each slide is presented. Some will be presented for 10 seconds, some for 20 seconds, some for 60 seconds, and so on.

That's the next step. And then I'm going to add a visible timer at the top that counts down how long each slide has been on the screen. When the timer gets to zero, the next slide will appear. I know that sounds bizarre, but that's what the page needs to work.

Thanks, and I appreciate your help.

Adam5000

2:34 pm on Jun 18, 2007 (gmt 0)

10+ Year Member



I've looked Logic's code over and it's too cryptic to work with. What I'd like to know with this post is why the code I wrote (at the beginning of this post) didn't work. Help!

colandy

7:13 pm on Jun 18, 2007 (gmt 0)

10+ Year Member



Because your writing the value of the array to the doc. The array values are 000.jpg and 001.jpg

The only way to show an image is via the img tag or via a backround-image.

Both use the attribute 'src' to determine the file to display. So to display an image you need an HTML tag that accept the 'src' attribute which should be an image file.

Adam5000

10:35 pm on Jun 18, 2007 (gmt 0)

10+ Year Member



You've got a good head on your shoulders Andy. This is the one I originally tried and couldn't get it to work. It may be something as simple as a syntax error. Your code works good and is a better version and I'm still trying to get a handle on arrays. Would you have a look at this one?

<html>
<head>
<title>Display image</title>
<script type="text/javascript">

var index=0

var photos=new Array()

photos new image()
photos[0].src="000.jpg"
photos new image()
photos[1].src="001.jpg"

</script>
</head>
<body>

<img src= photos[index].src>

</body>
</html>

Logician

11:53 pm on Jun 18, 2007 (gmt 0)

10+ Year Member



This version allows setting the period for each image. Just substitute your own filenames and add as many as you want, each followed by its period in seconds:

<img id='test' src='image1.gif'>

<script type='text/javascript'>

SlideShow=/*73637269707465726C61746976652E636F6D*/
{
 pics:[], holder:null, posn:0,

 init:function()
 {
  this.holder=document.getElementById(arguments[0]);

  for(var i=0, j=1; j<arguments.length; i++, j+=2)
  {
   this.pics[i]={img:arguments[j], period:arguments[j+1]}

   this.holder.src=this.pics[this.posn];
  }

  this.posn=this.pics.length-1;  
  this.swap();
 },

 swap:function()
 {
  if(++this.posn==this.pics.length)
   this.posn=0;

  this.holder.src=this.pics[this.posn].img;

  setTimeout('SlideShow.swap()', this.pics[this.posn].period*1000);
 }
}

SlideShow.init('test', 'image1.gif',10, 'image2.gif',2, 'image3.gif',5);

</script>

colandy

7:49 am on Jun 19, 2007 (gmt 0)

10+ Year Member



OK, Arrays are pretty simple really. You can setup the array at point of declaration if you know what the contents are going to be.

Example:

var Photos=new Array("000.jpg","001.jpg","002.jpg");

So Photos[0] is 000.jpg [1] is 001.jpg and so on

Alternatively you can declare the Array and set the values later.

Example:

var Photos= new Array();

Photos[0]="000.jpg";
Photos[1]="001.jpg";

Your requirement looks at having the src attribute of an img tag changed on a varying time basis, so if you have the images in an array, and the time intervals in an array you can set the timeout on a funtion using the timeout array and change the image source using the image source array.

So using my original code with a few amendments:

<SCRIPT type="text/javascript">
var photos = new Array("000.jpg","001.jpg","002.jpg","003.jpg");
var interval = new Array(5, 6, 2, 4); // Interval in seconds
var idx=0;

function showImage(index)
{

idx=idx+1;
if(idx>3) // Reset index if over the max no of images
{
idx=0;
}
var mimg=document.getElementById('test');
mimg.setAttribute('src',photos[index]);

// Set the timer to display next image
setTimeout('showImage('+idx+')', interval[index]*1000);

}

function initialise()
{
showImage(idx);
}

window.onload=initialise;
</SCRIPT>

This should do all you require.

Adam5000

5:50 pm on Jun 19, 2007 (gmt 0)

10+ Year Member



Andy. That's fabulous. That's teriffic. That allows the flexibility that makes the page work.

If you could fine tune it a bit, I'd like start and stop buttons at the top of the page, and a visible timer at the top, on the screen, that shows how long each slide has been on (it would automatically reset for each new slide, and pushing the start button more than once wouldn't make the timer speed up.) And finally after the timer counts down to zero on the last slide, display a final picture / slide on the screen that says "The End"

And then the page will be done.

colandy

12:59 pm on Jun 20, 2007 (gmt 0)

10+ Year Member



Not looking for much then.

Little bit of a re-write to cope with additional requests, this script will have a start button that will dissappear when pressed. This stops the user from pressing it again. Once pressed a stop button appears. If the stop button is pressed the message 'Stopped' appears and the start button re-appears while the stop button is hidden.

The count counts down the number of seconds left and changes the image just as the count gets to 0.

<SCRIPT type="text/javascript">
var photo=new Array("000.jpg","001.jpg","002.jpg","003.jpg");
var interval=new Array(2,4,6,1);
var idx=0;
var secs=interval[idx];
var timed;
var msg='';

function startClock()
{
msg="Stopped";

var bdiv=document.getElementById('start');
bdiv.style.cssText="display:none;";

var bdiv=document.getElementById('stop');
bdiv.style.cssText="display:block;";

var tdiv=document.getElementById('timer');
tdiv.innerHTML=secs;

var mdiv.document.getElementById('test');
mdiv.setAttribute('src','photo[idx]);

timed=setTimeout("startClock()",1000);

if(secs==0)
{

idx=idx-1;
if(idx>3)
{
msg="The End";
clearTimeout(timed);
stopClock();
}
else
{
var mdiv.document.getElementById('test');
mdiv.setAttribute('src','photo[idx]);
secs=interval[idx];
var tdiv=document.getElementById('timer');
tdiv.innerHTML=secs;
}
}
secs=secs-1;
}

function stopClock()
{
clearTimeout(timed);
var bdiv=document.getElementById('start');
bdiv.style.cssText="display:display;";

var bdiv=document.getElementById('stop');
bdiv.style.cssText="display:none;";

var mdiv=document.getElementById('test');
if(msg='The End')
{
mdiv.setAttribute('src','ending.jpg');
}
else
{
mdiv.setAttribute('src','stopped.jpg');
}
var mdiv=document.getElementById('timer');
mdiv.innerHTML=msg;
idx=0;
secs=interval[idx];
}
</SCRIPT>

<BODY>
<img id="test">
<div id="timer">&nbsp;</div>
<div id="start"><input type="button" onClick="javascript:startClock();" value="Start"></div>
<div id="stop"><input type="button" onClick="javascript:stopClock();" value="Stop"></div>
</BODY>

Now when you get your qualification can I have a copy of the Certificate to hang on my wall. :o)

colandy

1:04 pm on Jun 20, 2007 (gmt 0)

10+ Year Member



Just a quick note,

This is quick and dirty code, there is probably a better way of doing this, however, this is probably easier to understand.

Adam5000

10:58 pm on Jun 20, 2007 (gmt 0)

10+ Year Member



You're a great guy Andy and definitely at the top of the charts and I'm still trying to get your last set of code to run. All your other code works good, and this one I'm having a little trouble getting to run. I'm trying it with IE 7, Firefox 2.0.0.4 and Netscape 8.1.3 and I think these are the lastes versions. Both buttons appear on the screen and a multicolored (not a red X) box appears in the upper right corner. Would you try it out with one of the browsers I'm using? The browser version may make a difference. All your other code works great and I appreciate your help :)

colandy

7:18 am on Jun 21, 2007 (gmt 0)

10+ Year Member



This was a straight copy from my test server that worked. I usually don't post code unless already tested so it should work. I also run IE7 and FF (not sure which version) I'll re-check and let you know. later today.

colandy

7:59 am on Jun 21, 2007 (gmt 0)

10+ Year Member



OK, have rechecked and found a couple of probs with my typing. This works and have cut and paste this time. Obviously you need to ensure your images are in the same directory.

<HTML>
<HEAD>
<TITLE>Test</TITLE>
<SCRIPT type="text/javascript">
var photo=new Array("000.jpg","001.jpg","002.jpg","003.jpg");
var interval=new Array(2,4,6,1);
var idx=0;
var secs=interval[idx];
var timed;
var msg='';

function startClock()
{
msg="Stopped";
var bdiv=document.getElementById('start');
bdiv.style.cssText="display:none;";
var bdiv=document.getElementById('stop');
bdiv.style.cssText="display:block;";
var mdiv=document.getElementById('timer');
mdiv.innerHTML=secs;
var mdiv=document.getElementById('test');
mdiv.setAttribute('src',photo[idx]);
timed=setTimeout("startClock()",1000);
if(secs==0)
{
idx=idx+1;
if(idx>3)
{
msg="The End";
clearTimeout(timed);
stopClock();
}
else
{
var mdiv=document.getElementById('test');
mdiv.setAttribute('src',photo[idx]);
secs=interval[idx];
var mdiv=document.getElementById('timer');
mdiv.innerHTML=secs;
}
}
secs=secs-1;
}

function stopClock()
{
clearTimeout(timed);
var bdiv=document.getElementById('start');
bdiv.style.cssText="display:block;";
var bdiv=document.getElementById('stop');
bdiv.style.cssText="display:none;";
var mdiv=document.getElementById('test');
if(msg=="The End")
{
mdiv.setAttribute('src','Ending.jpg');
}
else
{
mdiv.setAttribute('src','');
}

var mdiv=document.getElementById('timer');
mdiv.innerHTML=msg;
idx=0;
secs=interval[idx];
}
</SCRIPT>
</HEAD>
<BODY>
<img id="test">
<div id="timer">&nbsp;</div>
<div id="start"><input type="button" onClick="javascript:startClock();" value="Start"></div>
<div id="stop" style="display:none;"><input type="button" onClick="javascript:stopClock();" value="Stop"></div>
</BODY>
</HTML>

Bernard Marx

1:51 pm on Jun 21, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I hope you don't mind if I point out a few things I have opinions on in Colandy's admirable code. I won't go too deep. Just a few extra tips.

[b]if(idx>[blue]3[/blue])[/b]

[b]if(idx==[blue]photo.length[/blue])[/b]

(I guess Colandy just missed this when cleaning up)
Hard coded numbers inside the logical structure should always be viewed with suspicion.
Use the length of the

photo
array.

--------------------------

[b]bdiv.style.[blue]cssText[/blue]="display:none;";[/b]

(..and similar)
[b]bdiv.style.[blue]display[/blue]="none";[/b]

Using the cssText property is handy on very particular occasions, but the potential downside is that it overwrites whatever may already be in the element's inline CSS (though not stylesheet rules).

In this case, it is better to apply to the display property, because there's no reason not to, and it keeps one's ass covered.

--------------------------

[b]timed=setTimeout([blue]"startClock()"[/blue],1000);[/b]

[b]timed=setTimeout([blue]startClock[/blue],1000);[/b]

setTimeout
&
setInterval
will (since a good while back) accept a function reference. This is more flexible then a string, more efficient too, and gives much more mileage for experimentation. A good avenue to explore.

--------------------------

[b]onClick="[blue]javascript:[/blue]startClock();"[/b]

[b]onClick="startClock();"[/b]

Event handlers have never needed or wanted the

javascript:
protocol. It's just a bad habit that refuses to lie down and die. The only reason there's no error caused is
... oh, some other time.

[edited by: Bernard_Marx at 1:52 pm (utc) on June 21, 2007]

hamidreza

1:57 pm on Jun 21, 2007 (gmt 0)

10+ Year Member



You can use this my friend

<html>
<head>
<title>Slide show 004</title>

<script type="text/Javascript">

var photos= new Array()

photos[0]= "<img scr="000.jpg">"
photos[1]= "<img scr="001.jpg">"

var index =0;

document.write (photos[index]);

</script>

</head>
</html>

colandy

2:14 pm on Jun 21, 2007 (gmt 0)

10+ Year Member



Bernard,

Many thanks for the improvements, as I'd mentioned on a previous post, this is what I call quick and dirty code but understandable hopefully. The improvements you mentioned are ideal and not done in mine partly due to ignorance on my part (being a reasonable beginner with JS).

This was a case of here's what I want, so I just did it as quickly and easily as possible.

Adam,

This should all work now, let us know..!

Adam5000

7:51 pm on Jun 21, 2007 (gmt 0)

10+ Year Member



Hey DrDoc. Calling DrDoc. Hi Dr., can you help me find some things? I need some lumber stuff. You know, items like 2 x 4's, nails, concrete, plywood, roofing shingles, and so on. Then a pick up truck to haul it all in, and some saws, drills, hammers and other things like that. I’m building a shrine to Andy.

Andy. You’re fabulous, magnificent, superb, tops, topnotch, stupendous, prodigious, and a lot of other good things. I’ve been working on this for at least two weeks and making slow progress at best. This is a terrific page and you’ve got a good head on your shoulders. This is going to be by far the most complicated page on my site, and it’s just what the page needs to make it work. You did a great job and compliments, kudos, and accolades to you.

And also thanks to everyone else who helped.. This page is done.