Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Font-awesome class fa is not being added with JQuery

I have a button where I want the HTML and font-awesome icon to change on an odd number of clicks and revert back on an even number of clicks.

For example, I have a button named mute. If a user clicks on the button, I want the html to change to unmute and the font-awesome class to be replaced. If the user clicks on the button again I want the button to revert back to mute and so on.

This code should work and it does change the URL and the class. But it doesn't add the font-awesome initialization class fa.

When I inspect the element, I get this

<button id="mute" class="btn btn-primary fa-volume-off"> Mute</button>

With JQuery's addClass method you can add multiple classes by separating them with a space. Based on this, the element should be this

<button id="mute" class="btn btn-primary fa fa-volume-off"> Mute</button>

Here is my code

var clicks = 0;
    $("#mute").click(function() {
            clicks += 1;
            if (clicks % 2 === 1) {
                    $(this).html(" Un-mute");
                    $(this).addClass("fa fa-volume-up");
                    $(this).removeClass("fa fa-volume-off");
                    apiswf.rdio_setVolume(0);
            }
            else {
                $(this).html(" Mute");
                $(this).addClass("fa fa-volume-off");
                $(this).removeClass("fa fa-volume-up");
                apiswf.rdio_setVolume(100);
            }
    });

I do not understand why the fa class does not get added.

like image 907
Richard Hamilton Avatar asked Mar 15 '23 20:03

Richard Hamilton


2 Answers

The problem is you removing fa class with removeClass method immediately after adding it . Change to this :

$(this).removeClass("fa-volume-off");
like image 86
Moti Korets Avatar answered Mar 25 '23 06:03

Moti Korets


Remove the class and then add the class. Swap the position of the two methods in both muting or unmuting

like image 39
Edward Manda Avatar answered Mar 25 '23 04:03

Edward Manda