« Return

PHP and jQuery append method ( fetch images without reloading the page )

demo


$(document).ready(function() {        

  <?php        
  $pattern   = '.jpg';
  $dir = './images';
  $sort = 1;
  $files = scandir($dir, $sort);
   
  foreach ($files as $key => $file) {     
  if (strpos($file, $pattern)):
  $gallery[] = $file;
  endif;
  }

  $i = count($gallery)-1;
  foreach ($gallery as $key => $file) {        
    if ( $key == $i ) { // if it’s the last array item 
      $output .=  "'" . $dir . '/' . $file . "'" . "\n"; // do not add the last coma
    } else {
      $output .=  "'" . $dir . '/' . $file . "'" . "," . "\n";
    }          
  }        
  echo 'var gallery = [' ."\n". $output . '];';
  ?>
  
  var steps = 5;        
  $('a').bind('click', function(event) {
     event.preventDefault(); // prevent window to scroll top
    for (var i = 0; i < steps; i += 1) {
      if ( gallery.length > 1 ) { $('.gallery').append('<img src="' + gallery.shift() + '" />'); }
      else { $(this).unbind('click').text('no more images to load'); }
    }
  });
  
  $('a').click();
  
});