5

Say a element has value 55:

<span id="some">55</span>

I want to:

  1. fade out the element
  2. set value 44
  3. fade in the element

So I tried:

$("#some").fadeOut("slow").html("44").fadeIn("slow");

But the above first sets the span's content to 44, and then fades out and fades in.

So I tried with a callback:

function fadeOutComplete(){
  $("#some").html("<%= @cc %>").fadeIn("slow");
}
$("#some").fadeOut("slow",fadeOutComplete);

Now this works, but it's looks and feels clunky. Is there some way to write this DRYer and more jQuery-er? (not even sure what I mean by jQuery-er!)

How could I pass in the element whose value is to be set and the value to be set to fadeOutComplete so I can make that callback sort-of generic?

Zabba
  • 64,285
  • 47
  • 179
  • 207
  • I don't know, but would also like to know how do you accomplish passing a value to a callback, something like '$("#some").fadeOut("slow",fadeOutComplete(44));'. Can use a global variable that gets set by the caller and read by the callback, but that's like 1980's programming style. – bloodcell Apr 24 '11 at 05:54
  • and here's how that's done - [JQuery pass more parameters into callback](http://stackoverflow.com/q/939032/374556) – bloodcell Apr 24 '11 at 06:07

4 Answers4

14

Check this...

$("#some").fadeOut("slow", function() {
   $(this).html("<%= @cc %>").fadeIn("slow");
});
  • You can pass an anonymous function, to prevent registering a named function that will no doubt only be used once.
  • Inside the callback of the complete for fadeOut(), this is pointing to the native DOM element. This allows you to reference it again in a DRY way.
alex
  • 479,566
  • 201
  • 878
  • 984
5

Same approach but with some cleanliness:

$('#some').fadeOut('slow',function(){
     $(this).html('somehtml').fadeIn('slow');
});
KoolKabin
  • 17,157
  • 35
  • 107
  • 145
0

This is a problem with the fade command. The command runs asyncronous, meaning while it is fading out the text is being changed. Look at this question for an answer: jQuery synchronous operation

Community
  • 1
  • 1
Jess
  • 8,628
  • 6
  • 49
  • 67
0

try like this:

$('#some').fadeOut('slow',function(){
$('#some').html('somehtml');
$('#some').fadeIn('slow');
});
2hamed
  • 8,719
  • 13
  • 69
  • 112