Search code examples
jquerysvgfont-awesome-5

Replacing and animating icon in fontawesome SVG


Before I switched to FA SVG the job of swapping an icon was quite simple -- remove old class, add two new ones. With SVG things are a bit more complex and while I was able to swap the icon I am not able to animate it...

HTML

<span id="myButton" class="btn btn-success">
    <i class="fas fa-check fa-fw fa-lg"></i> Click me
</span>

JS

$(document).on("click", "#myButton", function() {
    $(this).find("svg").attr("data-icon", "spinner").removeClass("fa-check").addClass("fa-spinner disabled");
});

What am I missing?


Solution

  • First: in order to change a data attribute i would suggest to use .data().

    In any case your issue is related to a class you forgot to add: fa-spin.

    Instead of add and remove classes I would suggest to use .toggleClass().

    The snippet:

    $(document).on("click", "#myButton", function(e) {
        var svg = $(this).find("svg");
        var newIcon = svg.data("icon") == 'check' ? 'spinner' : 'check';
        svg.data("icon", newIcon).toggleClass("fa-check fa-spinner fa-spin disabled");
    });
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
    
    
    <span id="myButton" class="btn btn-success">
        <i class="fas fa-check fa-fw fa-lg"></i> Click me
    </span>