Tanmim Hanifa
Tanmim Hanifa

Reputation: 73

How to call an image from a different src location to that of the clicked thumbnail image onto a separate div?

I am making a gallery webpage that has small thumbnails and one bigger container div to display a selected image. The thumbnail images are 300x300 stored in a thumbnail folder, however I would like to be able to click the thumbnail and have it call the full resolution image from an "images" folder that have the same name as its thumbnail counterpart. So thumbanil 1 would be src="thumb/image1.jpg" and when this is clicked, instead of calling "thumb/image1.jpg" onto the main container i would like it to call "images/image1.jpg".

Code:

HTML

<div class="containermain">
<img id="img-main" alt="main image" src="images/placeholder.png" />
<div class="clear"></div></div>
<div class="containerimg">
<img class="img" alt="thumbnail-image1" src="thumb/image1.jpg" />
<img class="img" alt="thumbnail-image2" src="thumb/image2.jpg" />
<img class="img" alt="thumbnail-image3" src="thumb/image3.jpg" />
<img class="img" alt="thumbnail-image4" src="thumb/image4.jpg" />
<img class="img" alt="thumbnail-image5" src="thumb/image5.jpg" />
</div>

Javascript

$(document).ready( function() {
    $("img.img" ).on( "click", function( event ) {
        $("#img-main").attr("src", $(this).attr("src"));
    });
});

So far this works, but the large imaged displayed on the main container is the thumbnail sized image and if i were to change the src to that from images folder with the full res image, the website will run too slow (the full images around 5mb-10mb each and I plan to have 18 images). Any help will be greatly appreciated thanks!

Upvotes: 1

Views: 297

Answers (1)

Shyju
Shyju

Reputation: 218702

Do a string replace.

$(document).ready( function() {
    $("img.img" ).on( "click", function( event ) {
        var currentSrc= $(this).attr("src");
        currentSrc=currentSrc.replace("thumb/", "images/");
        $("#img-main").attr("src", currentSrc);
    });
});

Here is a jsfiddle sample

But as TNC mentioned in the comment, the best solution is to keep an HTML 5 data attribute in your image tag for the full resolution image src

<img class="img" alt="thumbnail-image1" data-fullsize="images/image1.jpg" 
          src="thumb/image1.jpg" />

And read that and use it

$(document).ready( function() {
    $("img.img" ).on( "click", function( event ) {
        var newSrc= $(this).data("fullsize");          
        $("#img-main").attr("src", newSrc);
    });
});

Here is a sample of that

Upvotes: 0

Related Questions