FRESH SLIDING THUMBNAILS GALLERY WITH JQUERY AND PHP

    Rating: ★★★★☆
    View: 137
    Download: 202
    Từ khóa:

    In this tutorial we are going to create another full page image gallery with a nice thumbnail area that scrolls automatically when moving the mouse. The idea is to allow the user to slightly zoom into the picture by clicking on it. The thumbnails bar slides down and the image resizes according to the screen size.

    The scrolling functionality of the thumbnails bar is based on the great tutorial by Andrew Valums: Horizontal Scrolling Menu made with CSS and jQuery.
    Additionally, we will be using PHP to get the images and thumbs automatically from the folder structure. The folders will contain album sub-folders and we will add a select option to the gallery which allows to choose an album.

    Just like in the Sliding Panel Photo Wall Gallery with jQuery we will be using a resize function for the image displayed.

    We will also add an XML file that (optionally) contains the descriptions of the images.

    Another neat functionality that we are going to add is the changing cursor: depending in which mode and in which position of the full image we are, the cursor will change to a left or right arrow (for browsing the pictures), or to a plus or minus sign (for zooming in or out).

    The beautiful images in the demo are from the Models 1 – Photoshoots album from Vincent Boiteau’s photostream on Flickr.

    We also have a static version of the image gallery without the album option. You can find the demo link and the ZIP file in the end of this post.

    And don’t forget to check out the tutorial of the  mobile version of this gallery:Awesome Mobile Image Gallery Web App

    So, let’s start!

    THE FOLDER STRUCTURE

    Today we will start this tutorial by the folder structure since it is important for our PHP functionality.

    The necessary folders for the PHP to work are the images folder and the thumbs folder. They both need to be located in the root folder (where you will have the index.php file).

    Whatever album sub-folder will be in the thumbs folder, also needs to be in the images folder. So, if we have thumbs/album1/22.jpg we also need images/album1/22.jpgwhich will be the full-size image.

    With that organization we will be able to automatically display the album thumbnails and create a select box for all albums.

    In each album folder of the thumbs we will also have an XML file with the descriptions for the images. We will call that file desc.xml. Adding the description for images is not obligatory, i.e. we will just read the ones that are there. The structure of the XML file will be the following:

    
        
            1.jpg
            This is a nice description
        
        
            2.jpg
            red!
        
        
            3.jpg
            another one...
        
        ...
    

    It is important that we name the images in the name tag correctly.
    And also, make sure not to have any other files lying around in those folders.

    THE MARKUP AND PHP

    Let’s take a look at the HTML and also the PHP. We have a simple structure that will be dynamically “filled” by our PHP and JavaScript code:

    Vincent Boiteau's photostream
      $file"; ++$i; } } } } ?>

    The select box items get generated dynamically: we check the sub-folders in the images folder and put all the names in our items. The first album will be “selected” by default.

    When we click on one of the items we will call the thumbs.php (inside the ajax folder) from within the JavaScript. We will get back an array (JSON) with all the information that we need to build our thumbnails. Let’s look at that PHP code first and later we will go through the JS:

    $album      = $_GET['album'];
    $imagesArr  = array();
    $i      = 0;
     
    /* read the descriptions xml file */
    if(file_exists('../thumbs/'.$album.'/desc.xml')) {
        $xml = simplexml_load_file('../thumbs/'.$album.'/desc.xml');
    }
    /* read the images from the album and get the
     * description from the XML file:
     */
    if(file_exists('../thumbs/'.$album)) {
        $files = array_slice(scandir('../thumbs/'.$album), 2);
        if(count($files)) {
            foreach($files as $file) {
                if($file != '.' && $file != '..' &&  $file!='desc.xml') {
                    if($xml) {
                        $desc = $xml->xpath('image[name="'.$file.'"]/text');
                        $description = $desc[0];
                        if($description=='')
                            $description = '';
                    }
                    $imagesArr[] = array('src' => 'thumbs/'.$album.'/'.$file,
                        'alt'   => 'images/'.$album.'/'.$file,
                        'desc'  => $description);
                }
            }
        }
    }
    $json       = $imagesArr;
    $encoded    = json_encode($json);
    echo $encoded;
    unset($encoded);

    So, we basically get all the thumbnails of the requested album and prepare the information for each img element. The final element that we will then add to our HTML will contain an alt attribute with the full image location as value and a title attribute with the description of the regarding picture as value. The description of the image is taken from the XML file we mentioned before. With an xpath expression we get to the node “name” that contains the image name and then we get the text of the description. In the JS we will then say that the description should be the value of the “title” attribute.

    Now, let’s take a look at the style.

    THE CSS

    First, we will add some default styling to the body:

    body{
        font-family:Verdana;
        text-transform:uppercase;
        color:#fff;
        font-size:10px;
        overflow:hidden;
        background-color:#f9f9f9;
    }

    The current background color will be almost white but you can try other colors, it looks really wonderful with some!

    Let’s style the album bar for the title of the page:

    .albumbar{
        height:24px;
        line-height:24px;
        text-align:center;
        position:fixed;
        background-color:#000;
        left:0px;
        width:100%;
        top:0px;
        -moz-box-shadow:-2px 0px 4px #333;
        -webkit-box-shadow:-2px 0px 4px #333;
        box-shadow:-2px 0px 4px #333;
        z-index:11;
    }
    And also the info bar which will contain the description of each image:
    .infobar{
        height:22px;
        line-height:22px;
        text-align:center;
        position:fixed;
        background-color:#000;
        left:0px;
        width:100%;
        bottom:0px;
        -moz-box-shadow:0px -1px 2px #000;
        -webkit-box-shadow:0px -1px 2px #000;
        box-shadow:0px -1px 2px #000;
    }
    span#description, .albumbar span{
        text-shadow:0px 0px 1px #fff;
        color:#fff;
    }
    .albumbar span a{
        color:#aaa;
        text-decoration:none;
    }
    .albumbar span a:hover{
        color:#ddd;
    }
    The info bar and the album bar will be fixed and located at the top and bottom of the page.
    The select box and the inner list will be styled as follows:
    .albumSelect{
        height:18px;
        line-height:18px;
        position:absolute;
        right:5px;
        top:2px;
        width:120px;
    }
    .albumSelect .title{
        color:#f0f0f0;
        z-index:10;
        border:1px solid #444;
        background-color:#555;
        background-repeat:no-repeat;
        background-position:90% 50%;
        cursor:pointer;
        text-align:left;
        text-indent:10px;
        width:100%;
        position:absolute;
        top:0px;
        left:0px;
    }
    The title div will have a little triangle as background image. We define two classes, up and down, that we will then set dynamically depending on if the album list is expanded or not:
    .down{
        background-image:url(../icons/down.png);
    }
    .up{
        background-image:url(../icons/up.png);
    }
    The unordered list with all the albums will be styled as follows:
    .albumSelect ul {
        list-style:none;
        display:none;
        padding:0px;
        width:100%;
        border:1px solid #444;
        background-color:#555;
        margin:22px 0px 0px 0px;
        -moz-box-shadow:0px 0px 2px #000;
        -webkit-box-shadow:0px 0px 2px #000;
        box-shadow:0px 0px 2px #000;
    }
    .albumSelect ul li a{
        text-decoration:none;
        cursor:pointer;
        display:block;
        padding:3px 0px;
        color:#ccc;
    }
    .albumSelect ul li a:hover{
        background-color:#000;
        color:#fff;
    }
    The list is set to display:none in the beginning since we only want it to appear when the user clicks on the triangle to expand it.
    The loading container will be set to appear at the center of the page, with just a little bit more to the top since we have the thumbnails bar appearing sometimes. Setting top to 40% gives us what we need:
    #loading{
        display:none;
        width:50px;
        height:50px;
        position:absolute;
        top:40%;
        left:50%;
        margin-left:-24px;
        background:transparent url(../icons/loading.gif) no-repeat top left;
    }
    To make the thumbs bar scrollable by moving the mouse we need to give it a special style. The thumbsWrapper will be positioned absolutely and occupy the width of the window. We set the vertical overflow to hidden because we don’t want any scroll bar to appear on the right.
    The horizontal overflow will be managed in the JavaScript (it will be hidden).
    #thumbsWrapper{
        position: absolute;
        width:100%;
        height:102px;
        overflow-y:hidden;
        background-color:#000;
        bottom:0px;
        left:0px;
        border-top:2px solid #000;
    }
    The thumbsContainer will be the inner div that will have a width equal to the sum of all the thumbnail widths. We will calculate the width dynamically in the JavaScript, so we don’t define it in the class:
    #thumbsContainer{
        height:79px;
        display:block;
        margin: 0;
    }
    The thumbnail images will have the following style:
    #thumbsWrapper img{
        float:left;
        margin:2px;
        display:block;
        cursor:pointer;
        opacity:0.4;
        filter:progid:DXImageTransform.Microsoft.Alpha(opacity=40);
    }
    We give them a low opacity value since we want to add a hover effect.
    The imageWrapper that contains the full image has the following style:
    #imageWrapper{
        position:relative;
        text-align:center;
        padding-top:30px;
    }
    We add a top padding because we have the album bar at the top of the page. We don’t want the image to get hidden by it. The margin 0 auto will center the image horizontally:
    #imageWrapper img{
        margin:0 auto;
        -moz-box-shadow:2px 2px 10px #111;
        -webkit-box-shadow:2px 2px 10px #111;
        box-shadow:2px 2px 10px #111;
    }
    We also create a neat box shadow for all modern browsers :)
    Some of you might wonder why we set text-align center in the imageWrapper if we have the margin in the image. When we make things appear with the fadeIn function in jQuery, the display of the respective element becomes “block”. For that case our “margin:0 auto” will center the image. But for the case when we put the first image initially we need the inline centering property which is to give the parent “text-align:center”.
    And finally, we define the classes for the different cursor types:
    .cursorRight{
    .cursorRight{
        cursor:url("../icons/next.cur"), url("icons/next.cur"), default;
    }
    .cursorLeft{
        cursor:url("../icons/prev.cur"), url("icons/prev.cur"),  default;
    }
    .cursorPlus{
        cursor:url("../icons/plus.cur"), url("icons/plus.cur"), default;
    }
    .cursorMinus{
        cursor:url("../icons/minus.cur"), url("icons/minus.cur"), default;
    }

    OK, this is basically a hack and not really nice, but the reason for this ugliness is the browsers’ handling. The first url is the path for FireFox, the second one is for IE and the default value needs to be there again for Firefox. Read more about custom cursors and cross-browser compatibility here.

    Now, let’s get to the JavaScript.

    THE JAVASCRIPT

    Let’s go step by step through the jQuery code. I will not follow the order like it is in the script but by the usage of the functions. I hope that it will be easier to understand like that.
    In our

     $(function() { }
     we will add the following JavaScript:

    /* name of the selected album, in the top right combo box */
        var album   = $('#albumSelect div').html();
        /* mode is small or expanded, depending on the picture size  */
        var mode = 'small';
        /* this is the index of the last clicked picture */
        var current = 0;

    So, we will first declare some variables that we will need later and then we call:

    buildThumbs();

    The buildThumbs() function is going to get the current album and generate the images with the accoring source and information:

    function buildThumbs(){
        current=1;
        $('#imageWrapper').empty();
        $('#loading').show();
        $.get('ajax/thumbs.php?album='+album, function(data) {
            var countImages = data.length;
            var count = 0;
            var $tContainer = $('
    ',{ id : 'thumbsContainer', style : 'visibility:hidden;' }) for(var i = 0; i < countImages; ++i){ try{ var description = data[i].desc[0]; }catch(e){ description=''; } if(description==undefined) description=''; $(''+data[i].alt+'').load(function(){ var $this = $(this); $tContainer.append($this); ++count; if(count==1){ /* load 1 image into container*/ $('').load(function(){ var $first = $(this); $('#loading').hide(); resize($first,0); $('#imageWrapper').append($first); $('#description').html($this.attr('title')); }).attr('src',$this.attr('alt')); } if(count == countImages){ $('#thumbsWrapper').empty().append($tContainer); thumbsDim($tContainer); makeScrollable($('#thumbsWrapper'),$tContainer,15); } }).attr('src',data[i].src); } },'json'); }

    As we mentioned before, we will be using the thumbs.php file to get the info we need. When we are done building all the thumb images we append it to the thumbsWrapper and determine the size of the container with thumbsDim (line 36):

    /* adjust the size (width) of the scrollable container
    - this depends on all its images widths
    */
    function thumbsDim($elem){
        var finalW = 0;
        $elem.find('img').each(function(i){
            var $img        = $(this);
            finalW+=$img.width()+5;
        //plus 5 -> 4 margins + 1 to avoid rounded calculations
        });
        $elem.css('width',finalW+'px').css('visibility','visible');
    }

    Then we use makeScrollable (line 37) to make the thumbnail container scrollable by mouse move:

    //Get our elements for faster access and set overlay width
    function makeScrollable($wrapper, $container, contPadding){
        //Get menu width
        var divWidth = $wrapper.width();
     
        //Remove scrollbars
        $wrapper.css({
            overflow: 'hidden'
        });
     
        //Find last image container
        var lastLi = $container.find('img:last-child');
        $wrapper.scrollLeft(0);
        //When user move mouse over menu
        $wrapper.unbind('mousemove').bind('mousemove',function(e){
     
            //As images are loaded ul width increases,
            //so we recalculate it each time
            var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + contPadding;
     
            var left = (e.pageX - $wrapper.offset().left) * (ulWidth-divWidth) / divWidth;
            $wrapper.scrollLeft(left);
        });
    }

    The following function takes care of the click event on a thumbnail and also the hover event:

    /*
    clicking on a thumb loads the image
    (alt attribute of the thumb is the source of the large image);
    mouseover and mouseout for a nice spotlight hover effect
    */
    $('#thumbsContainer img').live('click',function(){
        loadPhoto($(this),'cursorPlus');
    }).live('mouseover',function(){
        var $this   = $(this);
        $this.stop().animate({
            'opacity':'1.0'
        },200);
    }).live('mouseout',function(){
        var $this   = $(this);
        $this.stop().animate({
            'opacity':'0.4'
        },200);
    });

    When a thumbnail is clicked we call the function loadPhoto (and we also pass the current cursor mode):

    /*
    loads a picture into the imageWrapper
    the image source is in the thumb's alt attribute
    */
    function loadPhoto($thumb,cursorClass){
        current     = $thumb.index()+1;
        $('#imageWrapper').empty();
        $('#loading').show();
        $('').load(function(){
            var $this = $(this);
            $('#loading').hide();
            resize($this,0);
            if(!$('#imageWrapper').find('img').length){
                      $('#imageWrapper').append($this.fadeIn(1000));
                      $('#description').html($this.attr('title'));
                }
        }).attr('src',$thumb.attr('alt'));
    }

    When want to adapt the size of the picture when we resize the window:

    /* when resizing the window resize the picture */
    $(window).bind('resize', function() {
        resize($('#displayed'),0);
    });

    The resize function is defined as follows:

    /* function to resize an image based on the windows width and height */
    function resize($image, type){
        var widthMargin     = 10
        var heightMargin    = 0;
        if(mode=='expanded')
            heightMargin = 60;
        else if(mode=='small')
            heightMargin = 150;
        //type 1 is animate, type 0 is normal
        var windowH      = $(window).height()-heightMargin;
        var windowW      = $(window).width()-widthMargin;
        var theImage     = new Image();
        theImage.src     = $image.attr("src");
        var imgwidth     = theImage.width;
        var imgheight    = theImage.height;
     
        if((imgwidth > windowW)				
    loading Đang tải...

    template được ưa chuộng