-1

This code in Meteor need to change the background color to yellow on click and back to white on another click, I tried few ways after reading others solutions but could not get it to work.

How can I change the color to yellow if it is white and to white if it is yellow. I need to code other things in the conditional statement as well later.

The HTML is:

<p>{{car.carID}} <strong class="toggleBackground">{{car.plate}}</strong></P>

Thanks

'click .toggleBackground': (e) => {
    //$(e.target).addClass('yellow'); // tried with css file for no avail
    
    console.log($(e.target).css("background-color"));

//tried === rgba(255, 255, 0) instead of yellow for no avail
    if($(e.target).css('background-color') === 'yellow'){ //<<< never true
      console.log('already yellow'); //<<< never called
      $(e.target).css('background-color', 'white');
    } else {
      console.log('will make yellow');
      $(e.target).css('background-color', 'yellow');

     }

  }
.white{
    background-color: #FFFFFF
}
.red{
    background-color: yellow
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Fred J.
  • 5,759
  • 10
  • 57
  • 106

2 Answers2

0

Please check below code, this will work for you. Here I have used classes to check which class is currently applied to the element and on that basis I am toggling classes so that when yellow color exist then it will remove that class and add white class and vice a versa.

  $(".toggleBackground").click(
            function () {
                    if($(this).hasClass("red")){
                    $(this).removeClass("red");
                   $(this).addClass("white");
                }
                else{
                $(this).addClass("red");
                 $(this).removeClass("white");
                }
                
            }            
        );
.white{
    background-color: #FFFFFF
}
.red{
    background-color: yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>{{car.carID}} <strong class="toggleBackground">{{car.plate}}</strong></p>
Krutika Patel
  • 420
  • 5
  • 16
-1

I found that this also works for me. What do you thing?

  'click .toggleBackground': (e) => {
    if(e.currentTarget.style.backgroundColor  === 'yellow'){
      e.currentTarget.style.backgroundColor  = 'white'
    } else {
      e.currentTarget.style.backgroundColor  = 'yellow'
    }
  }
Fred J.
  • 5,759
  • 10
  • 57
  • 106