How to replace a Font Awesome icon within link text with a different icon on link click?

I run a WordPress website that is edited by laypersons with no coding ability. The homepage consists of a list of standard html links (all of which are globally styled by css to resemble a button), the link text of which consists of a Font Awesome icon shortcode and the link title.

<a href="http://example.org/mypage/">[icon name="car"]Link Text</a>

For a user to add another link to the homepage, all they need to do is–while in the Visual Editor–select a Font Awesome icon via the tinyMCE menu, write their link text, and select both the icon and the link text when creating their link via the tinyMCE “create link” button.

Read More

The Font Awesome shortcode above results in the actual html being rendered like this:

<a href="http://mylink.org/mypage/"><i class="fa fa-car"></i>Link Text</a>

My question: when the link is clicked, I would like to have whichever icon is contained within that link to be replaced by the spinning Font Awesome gear/cog icon while the page is transitioning to the link target, thus replacing the link with the following:

<a href="http://mylink.org/mypage/"><i class="fa fa-cog fa-spin"></i></i>Link Text</a>

I just cannot figure out how to make this happen. I have tried many ways via jQuery but I am just learning this language and cannot seem to figure out how to do it.

In the meantime, I have accomplished a workaround by inserting both icons and using the :focus pseudoclass to show and hide one or the other after the link is clicked, but this solution does not seem to work on mobile and I don’t want to have the users have to have to insert both icons each time:

http://jsfiddle.net/qfnzmpzd/

Any solutions that require the individual making the link to manually add a class to the shortcode/html will not work. Thank you all for your help!!

Related posts

1 comment

  1. Since you tagged jQuery, you can add a .click() event:

    // When a link is clicked
    $('a').click(function() {
        // If the link contains an icon
        if ( $(this).find('.fa').length ) {
            // Remove the icon
            $(this).find('.fa').remove();
            // Prepend the spinner
            $(this).prepend('<i class="fa fa-cog fa-spin"></i>');
        }
    });
    

    Here’s a Fiddle.

Comments are closed.