Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace image using jQuery

Tags:

html

jquery

css

Here is my HTML:

<div id="show">
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR51FTd5w9iwfz_PLnUTUIbYBB0bCX6d3ue1ZSx3SJObNLGECEm"
>
</div>
<div id="thumbnails">
    <div id="thumbnail1">
        <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTPIzMxDNjQ_x4iUZ6WLo9R32QKCreu8PQGxcRHWmUw4hNcYmiR"
        width="100" height="100">
    </div>
    <div id="thumbnail2">
        <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR51FTd5w9iwfz_PLnUTUIbYBB0bCX6d3ue1ZSx3SJObNLGECEm"
        width="100" height="100">
    </div>
    <div id="thumbnail3">
        <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTsplNlIS3zRyy89UxlT5Nwu_Bn7m6w7iqMYXPF9q9MpLOG17XR"
        width="100" height="100">
</div>

My CSS:

#thumbnails div {
    float:left;
    border:1px solid;
}
#thumbnails div:hover {
    color:yellow;
}

So, I just want to change the div #show with any thumbnails below it when clicked. I've tried it using jQuery .attr('src', 'url'); but it doesn't work well.

Fiddle: http://jsfiddle.net/PemHv/

Thank you

like image 636
Brian Avatar asked Mar 01 '13 05:03

Brian


1 Answers

User .on() to assign click event to dom and .attr() to get attribute value of DOM.

$('#thumbnails img').on('click',function(){
   var src = $(this).attr('src');
   $('#show img').attr('src',src);
});

Explanation

in above code i assigned click event to the images inside div with id of thumbnails now first get the src attribute of the clicked image and set it into src variable.

then in next line it replace the src attribute of image inside show div.

like image 52
Dipesh Parmar Avatar answered Sep 20 '22 11:09

Dipesh Parmar