Kevin Steve Maningo
Kevin Steve Maningo

Reputation: 254

jQuery copy src of one image to another on click

What can I do to make this happen. I want that if I click the imgThumb1 image the src of this image is copied on the mainIMG, but the image don't change when I click it... what should I do?

$(document).ready(function(){
    $('.propertyResultImageThumb img[alt="imgThumb1"]').click(function(){
        var trial = $('img[alt="imgThumb1"]').attr('src');
        $("#mainIMG").attr("src", trial);
    });
});


<img alt="mainIMG" src="" id="mainIMG"/>
<img alt="imgThumb1" src="http://..../uploads/2012/09/Villa-Located-In-Almansa.jpg" />

Upvotes: 5

Views: 11386

Answers (4)

user5858
user5858

Reputation: 1221

If you want to copy an image without it to be downloaded from the server again(in case of captcha, it could change) then this code should be used:

$(function(){
    $('#first').click(function(){
        img_copy(document.getElementById('#first'),document.getElementById('#second'));
    });
});

//copy src to destination without destination to download the image
function img_copy(src,destination)
{
     var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    context.drawImage(src, src.width, src.height);
    var dataURL = canvas.toDataURL();
    destination.src = dataURL;
}



<img src="" id="first"/>
<img src="" id="second" />

Upvotes: 0

Vitalii Maslianok
Vitalii Maslianok

Reputation: 1631

$(document).ready(function(){
    $('img[alt="imgThumb1"]').click(function(){
        var trial = $('img[alt="imgThumb1"]').attr('src');
        $('img[alt="mainIMG"]').attr("src", trial);
    });
});

DEMO


my code

$(function(){
    $('#first').click(function(){
        $("#second").attr("src", $(this).attr('src'));
    });
});

<img src="" id="first"/>
<img src="" id="second" />

Upvotes: 5

rahul
rahul

Reputation: 7663

try wrapping your html in a container which will have class propertyResultImageThumb

<div class="propertyResultImageThumb ">
<img alt="mainIMG" src="" id="mainIMG"/>
<img alt="imgThumb1" src="http://..../uploads/2012/09/Villa-Located-In-Almansa.jpg" />
</div>     

and after that do it like this

$(document).ready(function(){
    $('.propertyResultImageThumb img[alt="imgThumb1"]').click(function(){
        var trial = $(this).attr('src');
        $("#mainIMG").attr("src", trial);
    });
});

Upvotes: 1

Abhidev
Abhidev

Reputation: 7253

You need to have a parent dom element with class name "propertyResultImageThumb " Check the jsfiddle

http://jsfiddle.net/erwKP/1/

Upvotes: 0

Related Questions