How to put all of the images from folder into CSS box
Tags: javascript,php,jquery,css,ajax
Problem :
I have a problem to load all images from a folder and display all of them in one CSS box (in html).
I want to make all the images like a video or gif maybe.
So each image will appear alternately until the last image is displayed.
Here is my php code :
camera.php
<?php
$img_dir = "image/";
$images = scandir($img_dir);
$html = '';
$html .='<ul>';
foreach($images as $img) {
if($img === '.' || $img === '..') {continue;}
if ( (preg_match('/.jpg/',$img)) || (preg_match('/.gif/',$img)) || (preg_match('/.tiff/',$img)) || (preg_match('/.png/',$img)) ){
$html .='<li><img src="'.$img_dir.$img.'" ></li>' ;
} else { continue; }
}
$html .='</ul>' ;
echo $html ;
?>
Here is my jquery code:
jquery.custom.js
jQuery('document').ready(function() {
$.ajax({
url: "camera.php",
type: "POST",
dataType: "HTML",
success: function( data ) {
jQuery('body').append(data);
},
error: function(jqXHR, data ) {
alert ('Ajax request Failed.');
}
});
});
Here is my CSS box :
#myGallery{
position:relative;
width:800px; /* Set your image width */
height:500px; /* Set your image height */
}
I can make all of the images appear , but I don't know how to display all of them in the CSS box and make all of them like a video.
I have 200 photos anyway.
Thanks for your help.
Solution :
For camera.php, you need to return the data in a format in which your ajax call can read it properly. Assuming that the call to images is returning correctly, you could do the following:
camera.php
$img_dir = "image/";
$images = scandir($img_dir);
$pictures = array();
foreach($images as $img) {
// Not sure how these are returning, so I'm making a guess after looking at your code
$picture = array(
"img" => $img_dir.$img
);
$pictures[] = $picture;
}
echo json_encode($pictures);
For the jQuery, you need to specify your dataType as json for it to return correctly. You also need to append the desired html and data to the body on a success return, and then call a function for the animation when that is done.
jquery.custom.js
jQuery('document').ready(function() {
var i = 0;
var request = $.ajax({
url: "camera.php",
type: "POST",
dataType: "json",
success: function(pictures){
var html = '<ul'>;
$.each(pictures, function(idx, picture){
html += '<li><img src="'+picture.img+'"></li>'
});
html += '</ul>';
$('body').append(html);
}
});
request.done({
loopThruImg();
});
function loopThruImg() {
var li = $('li');
li.eq(i).animate({
opacity: 1
}, 100, function () {
li.eq(i).delay(1000).animate({
opacity: 0
}, 100, function () {
i = i < (li.length - 1) ? i+1 : 0;
loopThruImg(i);
});
});
}
});
Some helpful CSS
ul {
list-style-type:none;
position: relative;
}
li {
position:absolute;
top:0;
opacity:0;
}
Awesome Stackoverflow answer that I borrowed heavily from