Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

Hi all- trying to work out an image gallery. Code below.

Edrol97

Coder
Screenshot 2024-03-11 at 20.42.36.pngScreenshot 2024-03-11 at 20.40.58.pngScreenshot 2024-03-11 at 20.37.26.png

Hi all, wondering about my code. Am wanting to build a slider gallery that loops and not really sure where to go from here. I've got the slider part but can't seem to find a way to loop it. I've seen various posts talking about const variables, and have copied code examples in and can't seem to figure out where I'm going wrong. The code I've copied is as followed:

JavaScript:
var image_count = 0;

function rollover (image_id, millisecs) {
  var image = document.getElementById(image_id);
  image.src = images[image_count];
  image_count++;

  if (image_count >= images.length) {
    image_count = 0;
  }

  setTimeout("rollover('" + image_id + "'," + millisecs + ");",millisecs);
}
HTML:
<img src="image1.png" id="img1" >

And for the loop to be started:
HTML:
<script language="javascript">
rollover("img1",2000);
</script>

I've got a tutor in coding who has advised against using var and instead says to use let as he says var is outdated, but can't figure out how to do it anyway! Does anyone have any ideas for what I'm sure is a ridiculously simple problem?
 
Last edited by a moderator:
I think it should be in rollover:
setTimeout(function(){rollover(image_id,millisecs);},millisecs);

var is good for that but you could use let instead. X E.
 
Hi there.

var, let and const are just keywords used to define variable/constants (variables whose value can't be changed). Although you should generally use const when you don't want a value to change, and let when the value can change, it doesn't (usually) change the outcome of your code, and probably shouldn't be the difference between working code and non-working code.

JavaScript:
setTimeout("rollover('" + image_id + "'," + millisecs + ");",millisecs);
The problem here is in the setTimeout() function at the end of the rollover() function. You passed a string rather than a function to the setTimeout() function, which although is valid, will not work as you expect it to, because image_id and millisecs aren't defined globally:
A string passed to setTimeout() is evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.

The solution would be to pass a function rather than a string to the setTimeout() function:
JavaScript:
setTimeout(() => rollover(image_id, millisecs), millisecs);

Or alternatively:
JavaScript:
setTimeout(rollover, millisecs, image_id, millisecs);
//            ^          ^          ^         ^
//       functionRef | delay | parameters to functionRef
 
Back
Top Bottom