Doug Molineux
Doug Molineux

Reputation: 12431

JQuery Fade In Attr Change

I was wondering if it was possible to add a fadeIn effect when an attr is changed for example I have this code working, when the user clicks on img2 imgmain's src is changed to img2's like this:

$('#img1').click(function() {
  $("#imgmain").attr("src","img1.jpg");
  });

  $('#img2').click(function() {
  $("#imgmain").attr("src","img2.jpg"); }

  );

Thank you!

Upvotes: 3

Views: 20115

Answers (5)

amertad
amertad

Reputation: 41

or...!

$('#MRMBIG').fadeOut('slow').attr('src',imgsrcclickshode).fadeIn('slow'); 

Upvotes: 4

dockeryZ
dockeryZ

Reputation: 3981

If you use the this keyword along with src, you don't have to iterate the image's source. For example

$('#img1').click(function() {
  var thisImage = this.src;
  $("#imgmain").fadeOut(function() {
    $(this).attr("src",thisImage).fadeIn();
  });
});

Better yet, you should give these images a classname also, this way it applies to them all. The above code will only work for the first image, while the code below, assuming they all have a class of thumb, will let you specify all of them

$('.thumb').click(function() {
  var thisImage = this.src;
  $("#imgmain").fadeOut(function() {
    $(this).attr("src",thisImage).fadeIn();
  });
});

Upvotes: 2

Šime Vidas
Šime Vidas

Reputation: 185993

You have redundancy in your code. Better:

$('#img1, #img2').click(function() {
  var src = $(this).attr("src");
  $("#imgmain").fadeOut(function() {
    $(this).attr("src", src).fadeIn();
  });
});

Usually, when you have multiple items, you use the class selector instead of listing the IDs of the items:

$(".images").click( ...

Upvotes: 1

armonge
armonge

Reputation: 3138

$('#img1').click(function() {
  $("#imgmain").fadeOut(function(){
  $(this).attr("src","img1.jpg");
  $(this).fadeIn();
  });
});

Upvotes: 4

Nick Craver
Nick Craver

Reputation: 630569

You can change it on the fadeOut() callback, like this:

$('#img1').click(function() {
  $("#imgmain").fadeOut(function() {
    $(this).attr("src","img1.jpg").fadeIn();
  });
});

Upvotes: 10

Related Questions