How to Create a Simple jQuery Gallery

There are dozens of jQuery plugins on the internet to help you create beautiful galleries. Most of them are more aesthetic than functional. This script helps you create a simple and lightweight jQuery photo gallery using unobtrusive JavaScript technique which allows users who have their JavaScript off still use the gallery.

Each image in the gallery is wrapped in a link element, and the script prevents the default behavior of the link, so users who have JavaScript off are still able to see the image in a new page, and those who have JavaScript on will see it in the gallery with fading effect.

HTML:

<div id="main-photo">
    <a href="img/1.jpg"><img src="img/1.jpg"></a>
</div>
<div id="thumbs">
    <a href="img/1.jpg"><img src="img/1.jpg" width="110" height="70"></a>
    <a href="img/2.jpg"><img src="img/2.jpg" width="110" height="70"></a>
    <a href="img/3.jpg"><img src="img/3.jpg" width="110" height="70"></a>
    <a href="img/4.jpg"><img src="img/4.jpg" width="110" height="70"></a>
    <a href="img/5.jpg"><img src="img/5.jpg" width="110" height="70"></a>
</div>

Javascript:

Remember to insert this after the jQuery library.

(function($) {
    $(function() {
        $('#thumbs a').click(function() {
            var newPhoto = $('');
            newPhoto.hide();
            var oldPhoto = $('#main-photo img');
            $('#main-photo').html(newPhoto);
            newPhoto.fadeIn(500);
            oldPhoto.remove();
            return false;
        });
    });
})(jQuery)

Have your say