1

I'm trying to define a hover function for when I hover over the buttons that I've created. For some reason, the if/else condition never seems to work. I'm trying to change the background color of my button if a particular condition is match upon hover and to a different color when the condition isn't a match. All that the function is doing is skipping the IF part completely and executing the ELSE irrespective of whether the condition is fulfilled or not. :

function clickHTML() {
  $("#html").css("background-color", "#F5FEFE");



}


$(".button").hover(function() {

  if ($(this).css("background-color") == "#F5FEFE") {

    $(this).css("background-color", "#AFF7F7");
    console.log('inside the if branch; color changed');

  } else {

    //alert($(this).css("background-color"));
    $(this).css("background-color", "#E4E4E4");
  }

}, function() {

  $(this).css("background-color", "#EDEDED");
  $("#html").css("background-color", "#F5FEFE");

});
h3,
html,
body {
  font-family: Helvetica, sans-serif;
  margin: 0px;
  padding: 0px;
}

#header-bar {
  width: 100%;
  height: 50px;
  background-color: #EDEDED;
}

h3 {
  padding: 14px 400px 0px 5px;
  float: left;
}

.button-group button {
  width: 100px;
  background-color: #EDEDED;
  margin: 10px 0;
  border: 1px solid black;
  color: black;
  padding: 5px;
  display: inline-block;
  text-align: center;
  text-decoration: none;
  font-size: 12px;
  float: left;
  border-radius: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet">

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js">
</script>

<body onload="clickHTML()">

  <div id="header-bar">

    <h3> CodePlayer </h3>

    <div class="button-group">

      <button id="html" class="button"> HTML </button>
      <button id="CSS" class="button"> CSS </button>
      <button id="js" class="button"> JavaScript </button>
      <button id="output" class="button"> Output </button>

    </div>
  </div>
</body>
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Pradyut Vatsa
  • 101
  • 2
  • 9

2 Answers2

1

If you console.log the value of

.css('backgroud-color')

You will see that its in rgb format. But you are trying to compare with hex. You can try to convert it before the comparison with

var rgbToHex = function (rgb) { 
  var hex = Number(rgb).toString(16);
  if (hex.length < 2) {
       hex = "0" + hex;
  }
  return hex;
};
Reidenshi
  • 180
  • 8
0

You should use

if ($(this).css("background-color") == "rgb(245, 254, 254)") {

instead of

if ($(this).css("background-color") == "#F5FEFE") {

End for the rest of the colors use RGB instead of HEX to.

Aiken
  • 272
  • 1
  • 8