views:

760

answers:

4

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

+4  A: 

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);
karim79
I might be tempted to use .live also, depending on how many thumbs/other live events etc
redsquare
Beware that live doesn't work on blur, focus, mouseenter, mouseleave, change, submit
James Wiseman
@redsquare - good point, if the thumbs are loaded in ajaxily, that would be the way to go - I'll throw that in.
karim79
@James. this is click....
redsquare
A: 

karim79's answer could be shortened slightly:

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

But otherwise, good answer!

James Wiseman
A: 

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.

Juicy Scripter
A: 
$().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', ''));
        });
    });

});
FerrousOxide