0

My background: I am new to javascript/jQuery and I am finding them harder to learn than any other languages. So forgive me if this is a stupid question or my programming logic is flawed.

Problem: I want to scan a directory for image files, return an array. I want to loop thru the array changing the css background-image in a div to display the images. I've seen many solutions that hide and fade in HTML ul/li elements. I don't want to hard code the images into the HTML. I have no problem with the PHP portion of this, (I found PHP quite easy to learn). The code below is working, but it only displays the last image in the array as it loops without pausing. Is there a way to pause a jQuery .each? Or is it my design in the first place? I know that this loop will only run once. I planned on solving that problem once I got this bit of code to work. I have tried delay, setInterval, setTimeout to no avail. I am probably using them incorrectly as well.

$(document).ready(function() {
    $(function() {
        $.post('getimagefiles.php', { dir : './images/banner/'},
        function(data) {
            var images = data;
                $.each(images, function(key, val) {
                    arg= 'url(' + val + ')';
                    /*alert(arg);*/
                    $('div#canvas').css("background-image", arg).delay(3000);
                });
        }, 'json');
    });
});
Jo E.
  • 7,822
  • 14
  • 58
  • 94
  • I am sorry. I searched through this site for hours now and didn't find what I was looking for. I'll continue to search I guess. – Jolynne Jul 26 '15 at 16:03
  • read docs for `delay()` ... only works on methods that can be queued like animations or functions you push to a queue – charlietfl Jul 26 '15 at 16:07
  • I've solved this problem. I didn't realize that css changes are not done until the script they are in completes. Explains why I only saw the last image in the array. The following code is the solution that worked for me. – Jolynne Aug 05 '15 at 01:39
  • function getImage() { $.post('getImage.php', { dir : './images/banner/' }, function(data) { var images = data; $.each(images, function(key, val) { imageFiles[key] = 'url(' + val + ')'; }); }, 'json'); }; function display() { $('div#canvas').hide(); $('div#canvas').css("background-image",ImageFiles[imageIndex]); $('div#canvas').fadeIn(2000); if(++imageIndex >= imageFiles.length) imageIndex = 0; }; $(document).ready(function() { getImage(); time = 6000; displayImage(); setInterval(display, time); // (1000 msec = 1 sec) }); – Jolynne Aug 05 '15 at 01:46

0 Answers0