Search code examples
jqueryjquery-uitextjquery-effectscss

Cross-fade for inline text elements with jQuery


I am looking for a way to properly animate/crossfade inline anchor elements with jQuery. There are several solutions out there for block elements, but nothing so far for inline-elements.

My alternative text for each individual word comes from an attribute within the element:

<a data-r="nerd">word</a>​

But if I try to fadeout, replace the text and fade in, like here:

jQuery(document).ready(function($) {
$('a').click(function(index) {
    $(this).fadeOut(500, function() {
        $(this).text($(this).attr("data-r"));
    });
    $(this).fadeIn(500);
    });
});​

I am not getting the cross-fade effect that I would like, but a fadeout followed by a fadein, as you can see in this demo.

I'd be very grateful for any tips you might have.


Solution

  • Here's what i came up with:

    $('a').click(function(index) {
      var clone = $(this).clone();
      clone.css('position', 'absolute');
      clone.css('left', $(this).position().left);
      clone.css('top', $(this).position().top);
      $('body').append(clone);
    
      $(this).hide();
      $(this).text($(this).attr("data-r"));
    
      clone.fadeOut(500, function() {
        clone.remove();
      });
      $(this).fadeIn(500);
    });
    a { font-size: 60px; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <p>
        <a data-r="nerd">word</a><br>
        <a data-r="dork">word</a>
    </p>

    You may have to adjust this to work with different line-heights, though.