Search code examples
javascriptjqueryfont-awesome-5

How to add an if else statement in my code?


I am trying to an if/else statement added to this code where the toggle is already clicked to be able to click it again and change to another color

HTML

<a class="reme" href="#"><i class="far fa-circle"></i> Remember Me</a>

JQUERY

$(".reme").click(function(){
$(this).css("color", "#1ABC9C");
$(this).find('i').toggleClass('far fa-cirle fas fa-circle');
});

Solution

  • You can add a style to your CSS and then just toggleClass for the button itself - as demonstrated below.

    Let me know if you wanted something else.

    I have also added an if version below, but would advise against using it.


    Demo

    // Click event
    $(".reme").click(function() { 
    
      // Toggle class on the button
      $(this).toggleClass("green-text");
    
      // Unchanged
      $(this).find('i').toggleClass('far fa-cirle fas fa-circle');
    
    });
    .green-text {
      color: #1ABC9C;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <button class="reme">Toggle</button>


    Alternative

    You can use an if statement if you'd like, and check the inline .css value of color... but this is definitely not the best way of doing this. Toggling classes will be much better for this particular use case.

    // Click event
    $(".reme").click(function() {
    
     // Check if the color is set inline to the rgb version of your color - as when changed this way it enters the hex as rgb 
     if ( $(this).css("color") == "rgb(26, 188, 156)")  {
        
        // Make it black if it is
        $(this).css("color", "black");
        
      } else {
      
        // Set it as green if not
        $(this).css("color", "#1ABC9C");
        
      }
      
      $(this).find('i').toggleClass('far fa-cirle fas fa-circle');
      
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    
    <button class="reme">Toggle</button>