Desperately trying to toggle a font awesome icon

Soldato
Joined
27 Dec 2005
Posts
17,310
Location
Bristol
As title, I'm probably overlooking something really simple. Just trying to get the bars icon to change to a times and vice versa when clicked. Here's the code.

Code:
<div id="mobilebutton"><i class="fa fa-bars"></i></div>

Code:
$( "#mobilebutton" ).click(function() {
  $( "#mobilenavoverlay" ).slideToggle( "slow", function() {
  });
        $(this)
        .find('[data-fa-i2svg]')
        .toggleClass('fa-times')
        .toggleClass('fa-bars');
});

jQuery code is within a $(document).ready(function(){. I've followed the instructions on https://fontawesome.com/how-to-use/svg-with-js#with-jquery and used their code, but nada. Heeelp!
 
You don't have a 'data-fa-i2svg' attribute on that element, so it won't be found. Using '.fa' instead works.

That doesn't work because I'm using the SVG version of FA. The data tag is from their documentation; "If you absolutely need to attach events to the icon you can use the data-fa-i2svg attribute but you need to allow for the dynamic creation of the svg element."
 
I think you'd use the data tag like this:

*snip*

Adding the data-fa-i2svg attribute manually to any icon prevents it from displaying.


Not sure why you're being so passive aggressive. Your post contradicts itself now you've read their documentation re: the data-fs-i2svg attribute being added.

I've completely copied FA's code now, below, and still nothing. The #mobilenavoverlay displays so it's finding the object, just not able to toggle the class.

Code:
<button>Open up <i class="fa fa-angle-right"></i></button>

<script>
document.addEventListener('DOMContentLoaded', function () {
    $('button').on('click', function () {
        $( "#mobilenavoverlay" ).slideToggle( "slow" );
      $(this)
        .find('[data-fa-i2svg]')
        .toggleClass('fa-angle-down')
        .toggleClass('fa-angle-right');
    });
  });
  </script>
 
No problem :). Thanks for your help so far.

So that jsfiddle link doesn't work for me (as in, the code doesn't toggle the icon). Not a browser issue though since the example on FA's website works.

I hate jS!
 
Back
Top Bottom