0

hi im new to using javascript and im stuck in a problem. so i have this folder which contains image that i need to diplay and i was using javascript to show these images. every images is named as Slidex.PNG where x is the number of slide. what i have so far is

var baseUrl = "{{ asset($chkdir) }}/";
        alert(baseUrl);
        var pictureIndex = 1;

        function next()
        {

            var image_url = baseUrl + 'Slide' + pictureIndex + '.PNG';
            document.getElementById("viewer").src = image_url ;
            pictureIndex++;
        }

it is working so far but my problem is say for example i have 5 images inside the folder after the Slide5.PNG it still loads Slide6.PNG which displays a broken image i just wanted to know if there is a way to get the total number of image files inside the folder. Any advices? thanks in advance!

BourneShady
  • 955
  • 2
  • 17
  • 36

2 Answers2

3

You could have an off-screen / buffer image to test for an image at the new url before assigning the url to your page element. If the load fails you can prevent the src from being assigned and prevent any future load attempts.

Also by using a buffer image, your image is downloaded by the browser already, and as such there will be no delay to display the image on your page whilst the new url is downloaded.

For this example, I've assumed you're using a timer to call next() repeatedly:

var pictureIndex = 1;
var baseUrl = "{{ asset($chkdir) }}/";
var image_url = undefined;
var timer = setInterval(next, 5000);

var tester = new Image();
tester.onload = imageFound;
tester.onerror = imageNotFound;

function next()
{
  image_url = baseUrl + 'Slide' + pictureIndex + '.PNG';
  tryLoadImage(image_url);
}

function tryLoadImage(url) {
  tester.src=url;
}

function imageFound() {
  document.getElementById("viewer").src = image_url;
  pictureIndex++;
}

function imageNotFound() {
  // perform some function to stop calling next()
  clearInterval(timer);
}
Neil Cross
  • 502
  • 3
  • 9
1

You can use an API where the data will have the path to your images and the server will make this count and send to the user. Or you can use a templates where the server will serve HTML's with all files and image paths.

PHP template example:

    <img src="<php>print(imagePath);<?php>">

I don't know what you are doing, but I don't consider that a good practice, since that is a server side task and you are doing that on client with a lot of limitations.

But take a look on this question where the javascript checks the size of the file to see if the image is broken or not: Determining image file size + dimensions via Javascript?

Community
  • 1
  • 1
Tiago Fabre
  • 739
  • 5
  • 18