Search code examples
jqueryhtmlfadeinfadeoutcross-fade

custom jQuery function to crossfade fonts


I need a custom jQuery function that lets me target all text elements with a certain class, say class="fontfade", and cause those elements to crossfade from their original font to a new font. I can change font like this

$(".one").css("font-family", "Comic Sans MS");

and HTML Code is

<p class="one">Demonstrate transition.</p>

The tricky thing here is crossfading. I want a smooth transition from previous font to new font. I mean text with previous font will fadeOut and text with new font will fadeIn. So at some point both text with different font can be seen.

I am trying like this

$(".one").fadeOut(3000);
$(".one").css("font-family", "Comic Sans MS");
$(".one").fadeIn(3000);

not working..


Solution

  • <p><a href="#" class="one">Demonstrate transition.</a></p>
    
    <script>
        $(document).on('click', '.one' ,function() {
            $(".one").fadeOut(3000);
            $(".one").css("font-family", "Comic Sans MS");
            $(".one").fadeIn(3000);
        });
    </script>
    



    Edit: after re-reading your post and comment, perhaps this is what you're after?

    <script>
        .old {
            font-family: helvetica;
        }
        .new {
            font-family: comic sans;
        }
        .hide {
            display: none;
        }
    </script>
    
    
    <p><a href="#" class="one">Demonstrate transition.</a></p>
    <div class="old">Old Font</div>
    <div class="new hide">New Font</div>
    
    <script>
        $(document).on('click', '.one' ,function() {
            $('.old').fadeOut(500);
    
            $('.new').fadeIn(500, function(){
                $(this).removeClass('hide').css("font-family", "Comic Sans MS");
            });
        });
    </script>