Replace image with jQuery

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 div #showto any thumbnails below it when clicked. I tried it with help jQuery .attr('src', 'url');, but it does not work.

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

thank

+5
source share
4 answers

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

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

Explanation

in the above code, I assigned an event clickfor the images inside divwith an identifier thumbnails, now first get src attribute clicked imageand set it to a variable src.

src attribute show div.

+8

: http://jsfiddle.net/PemHv/3/

JQuery

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

HTML ( ):

<div id ="show">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR51FTd5w9iwfz_PLnUTUIbYBB0bCX6d3ue1ZSx3SJObNLGECEm" width="200" height="200">
    </div>

<div id="thumbnails">
<div class="thumbnail">
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTPIzMxDNjQ_x4iUZ6WLo9R32QKCreu8PQGxcRHWmUw4hNcYmiR" width="100" height="100">
    </div>

<div class="thumbnail">
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR51FTd5w9iwfz_PLnUTUIbYBB0bCX6d3ue1ZSx3SJObNLGECEm" width="100" height="100">
    </div>
    </div>
+1

http://jsfiddle.net/PemHv/9/

$('#thumbnails div').click(function(){
    var path = $(this).find('img').attr("src");
    //console.log(path)
    $('#show img').attr("src", path );
});
+1
source
$('#show')
    .children()
    .on('click', function(event) {
        $(event.target).attr('src', 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTPIzMxDNjQ_x4iUZ6WLo9R32QKCreu8PQGxcRHWmUw4hNcYmiR');
    });
0
source

All Articles