Home > Software engineering >  How to change the button background color using jQuery selectors and if else statement?
How to change the button background color using jQuery selectors and if else statement?

Time:06-14

I need to change btn1 background color from transparent to green when someone click on it. If the user clicks on the button again btn1's background color should be change from green to transparent. Is this following if condition is valid or not?

if(('#btn1').css("background-color")== "green")
function vote(str){
  
  if(str==1){
        
        if(('#btn1').css("background-color")== "green"){
      
                $('#btn1').css("background-color","");
      
      
        }else{
      
                $('#btn1').css("background-color","green");
      
      }
  
  }else{
  
    $('#btn2').css("background-color","red");
  }

}
</script>
</head>
<body>
<button id="btn1" onclick="vote(1)" >Up Vote</button>
<button id="btn2" onclick="vote(2)" >Down Vote</button>

CodePudding user response:

You can use seperate classes for each color, and then use the toggleClass function to change them as required:

$("button").on("click", (e) => {
  $(e.target).toggleClass("transparent green")
})
.green {
  background-color: green;
}

.transparent {
  background-color: rgba(0, 0, 0, 0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button >hello</button>

CodePudding user response:

You can try to use css to achieve the effect you want, and use the addClass and toggleClass functions to toggle and add classes.

addClass()

Adds the specified class(es) to each element in the set of matched elements.

toggleClass()

Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.

$("#btn1").on("click", function() {
  $(this).toggleClass('background-green');
});

$("#btn2").on("click", function() {
  $(this).addClass('background-red');
});
.background-red {
  background-color: red !important ;
}

.background-green {
  background-color: green !important;
}

.background-transparent {
  background-color: transparent;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn1" >Up Vote</button>
<button id="btn2">Down Vote</button>

  • Related