Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap image src with jquery

I have one big image and small thumbs, i am trying to swap their src with each other. Here i am changing thumb img in bottleWrapper img, but i want to swap their src. Pls help!

HTML

<div class="bottlesWrapper">
  <img src="bottle1.png" />
</div>

<div class="thumbs">
   <img src="bottle2.png" />
</div>

SCRIPT

<script>
$('.thumbs a').each(function() {
    $(this).click(function() {
       var aimg = $(this).find("img")

      $('.bottlesWrapper img').fadeOut('fast',function(){
         $(this).attr('src', $(aimg).attr('src')).fadeIn('fast');
      });

    });
});
</script>

EDIT

Thanks all :)

I actually forgot to give out one information that I have various thumbs, this answer suits best! Thank you all for your precious inputs!

$('.thumbs img').click(function() {
    var thmb = this;
    var src = this.src;
    $('.bottlesWrapper img').fadeOut(400,function(){
        thmb.src = this.src;
        $(this).fadeIn(400)[0].src = src;
    });
});
like image 931
itsMe Avatar asked Mar 29 '13 06:03

itsMe


People also ask

How to change image onclick in jQuery?

Answer: Use the jQuery attr() Method You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.


2 Answers

To SWAP images do like:

LIVE DEMO

$('.thumbs img').click(function() {
    var thmb = this;
    var src = this.src;
    $('.bottlesWrapper img').fadeOut(400,function(){
        thmb.src = this.src;
        $(this).fadeIn(400)[0].src = src;
    });
});

If you have multiple 'galleries' do like: http://jsbin.com/asixuj/5/edit

like image 143
Roko C. Buljan Avatar answered Sep 21 '22 13:09

Roko C. Buljan


ther is no <a> tag in your question ..so assuming its img.. on click of thumbs img.. the bottlesWrapper will get swaped..

try this

updated

 $('.thumbs img').click(function() {
   var img=$(this).attr('src');

  $('.bottlesWrapper img').fadeOut('fast',function(){
     $(this).attr('src', img).fadeIn('fast');
  });

  $(this).fadeOut('fast',function(){
     var bottlersImg=$('.bottlesWrapper img').attr('src');
     $(this).attr('src', bottlersImg).fadeIn('fast');
  });

});

NOTE: and you don't need each loop ... jquery dose that by using a class selector works..

like image 33
bipen Avatar answered Sep 22 '22 13:09

bipen