Question

I have a large image in a gallery that needs to change when one of the thumbnails is clicked within a unordered list below. The images are coming in dynamically so the jquery script needs to be able to take the src of the thumbnail, remove "-thumb" from the filename, and then replace the large image with the new source.

Please let me know what is my best approach to a gallery like this.

Thanks in advance.

-B

Was it helpful?

Solution

Something like:

$('img.thumb').click(function() {
    var src = $(this).attr('src');
    $('#bigImage').attr('src', src.replace(/-thumb/,''));
});

The below examples apply if your thumbs are being loaded in via ajax:

(1) Using Events/live:

$('img.thumb').live("click", function() {
    var src = $(this).attr('src');
    $('#bigImage').attr('src', src.replace(/-thumb/,''));
});

(2) As a callback to one of jQuery's ajax methods (e.g.):

function initThumbs()
{
    $('img.thumb').click(function() {
        var src = $(this).attr('src');
        $('#bigImage').attr('src', src.replace(/-thumb/,''));
    });
}

$('#thumbsDiv').load('thumbs.php?p=2', initThumbs);

OTHER TIPS

karim79's answer could be shortened slightly:

$('img.thumb').click(function() {
    $('#bigImage').attr('src', $(this).attr('src').replace(/-thumb/,''));
});

But otherwise, good answer!

The only addition to karim79's is:

In a case the thumbnails are placed within same parent binding an event on that parent would be much better (elegant?) solution that binding events on all thumbnails. The event is propagated, so you can find thumbnails by checking event target.

$().ready(function() {

    //get all images from unordered list and apply click function
    $('ul#myList img').each(function() {
        $(this).click(function() {
            $('#mainImage').attr('src', $(this).attr('src').replace('-thumb', ''));
        });
    });

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top