Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fade out, set value, fade in; but do it 'better'

Tags:

jquery

effect

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?

like image 936
Zabba Avatar asked Dec 02 '22 02:12

Zabba


1 Answers

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.
like image 78
alex Avatar answered Jan 05 '23 09:01

alex