views:

67

answers:

2

I'm trying to use the following code to make an image fadeOut and, only when it's faded out, change its source, and then make it fadeIn again:

$('.liitem').click(function() {
 $('#imagen').fadeOut('slow', function() {
  var rutaimagen = $(this).find('a').attr("href");
  $('#imagen').attr("src",rutaimagen).load(function(){     
   $('#imagen').fadeIn('slow');
   });
 });
 return false;
});

...but it doesn't work!! I've tried removing the callback function in fadeOut, and then it works but you can see for a moment the new image abruptly replacing the previous one (because it loads before the fadeOut effect has finished), then fading out, and then in again:

$('.liitem').click(function() {
 $('#imagen').fadeOut('slow');
  var rutaimagen = $(this).find('a').attr("href");
  $('#imagen').attr("src",rutaimagen).load(function(){     
   $('#imagen').fadeIn('slow');
   });
 return false;
});

Obviously I'd prefer a working version of the 1st snippet.

You can see that I am using a function that triggers the fadeIn effect only when the new image is loaded, which is logical in case the new image is very big and needs more time. I don't mind if it stays white while it loads, I can implement a loader .gif for that. But I don't know if this .load(function(){}); is interfering the whole thing.

+2  A: 

One thing I notice that's different between your two examples:

$(this).find('a').attr("href");

In the first, "this" is #imagen, in the second "this" is .liitem. Does that have anything to do with it?

darkporter
Thank you. You pointed me to the right direction. In fact I realized my question was a little dumb. This is my code now and it works perfectly.
Alextronic
A: 

Thanks darkporter. This is my code now and it works:

$('.liitem').click(function() {
  var liitem = $(this);
 $('#imagen').fadeOut('slow', function() {
  var rutaimagen = liitem.find('a').attr("href");
  $('#imagen').attr("src",rutaimagen).load(function(){
   $('#imagen').fadeIn('slow');
   });
 });
 return false;
});
Alextronic
Nice. That's the old "`var self = this`" trick to preserve the old "this".
darkporter
Thanks Darkporter. I have not been using jQuery for that long. I am surprised by the posibilities!
Alextronic