Question

When a user clicks on a small thumbnail image I then want a larger div element on the same page to then display that image. So far that works with the following code:

$(document).ready(function () {
    $("img#thumb").click(function () {              //when image with ID thumb is clicked change src 
    var imgpath = $(this).attr("src");
    $("img#cover").attr("src", imgpath);
});

});

However I now want the old image to fade out while simultaneously switching the new one depending on whichever thumbnail the user clicks. I track the thumb clicked by making jQuery save the src file to a variable then put that in a new path using .attr()

How can I do this?

Was it helpful?

Solution

Not sure i catched what you need but this should be ok, try :

  $(function(){
        $("img#thumb").bind('click',function () {               
        var img = $(this).clone(); //this clones the img, so you do not need to re-load that using src path
        $(this).fadeOut(500);
        $("img#cover").hide().html(img).fadeIn(500); //remove .hide() segment if you just are hiding by css rules

        });

        });

OTHER TIPS

I guess you mean to fade out the cover image.

If that you can try:

$("img#cover").fadeOut();
$("img#cover").attr("src", imgpath);

You should be rather on event rather than click event of jquery. You could even leverage live but that's now deprecated.

Here's my interpretation of what you are trying to accomplish: DEMO.

HTML

<img class="thumb" src="/img/logo.png" width="100" />
<img class="thumb" src="http://www.wpclipart.com/sign_language/thumbs_up_large.png" width="100" />

<div class="cover">
    <img id="cover" width="400"/>
    <img id="cover-old" width="400"/>
</div>
​

Javascript

$(function() {
    $("img.thumb").on('click', function() { //when image with ID thumb is clicked change src 
        var imgpath = $(this).attr("src");
        $("#cover-old").attr('src', $("#cover").attr('src'));
        $("#cover-old").show();
        $("#cover").hide();
        $("#cover").attr("src", imgpath);
        $("#cover-old").fadeOut('slow');
        $("#cover").fadeIn('slow');
    });
});​

CSS

.cover {
    position: relative;

}
.cover img {
    position: absolute;
}
​
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top