Change background color of div using conditional statement

css, html, javascript, jquery

Solution

You can put the check in the complete function of toggle

$(document).ready(function() {

  $("#aside").hide();
  $("#asidebar").show();

  $('#asidebar').mouseenter(function() {
    $("#aside").toggle("slide", function() {
      var onOrOff = $('#asidebar').css("background-color");
      if ($('#aside').is(":visible")) {
        $("#asidebar").css("background-color", "blue");
      } else if ($('#aside').is(":hidden")) {
        $("#asidebar").css("background-color", "yellow");
      }
    });

  });

});
#asidebar {
  float: right;
  /* top: -205px; */
  position: relative;
  /*
    Editing purposes */
  background-color: rgba(120, 120, 120, 0.5);
  width: 25px;
  /*min height of container */
  height: 400px;
  margin: 5px;
  padding: 1px;
  font-family: helvetica;
}

#aside {
  float: right;
  /* top: -205px; */
  position: relative;
  /*
    Editing purposes
    background-color: blue; */
  width: 250px;
  border-left-style: dashed;
  border-color: rgba(120, 120, 120, 0.5);
  /*min height of container */
  margin: 5px;
  padding: 0;
  font-family: helvetica;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="asidebar">Mouse Over</div>
<div id='aside'>Slide box</div>

Problem

I have 2 divs side by side and by default one is hidden and one is visible. I have a jQuery function which, when mouseenter the visible div, the hidden one shows. And when mouseenter again, it becomes hidden again. (This is for a login box) However - I want the always visible div (the mouseenter target) to change color depending on what state the toggled div is in. So far, I can get it to change color upon first mouseenter but it won't change again after that. Here is the code I have so far: ``` <script> $(document).ready(function () { $("#loginBox").hide(); $("#sideBar").show(); $('#sideBar').mouseenter(function () { $("#loginBox").toggle("slide"); if ($('#loginBox').is(":visible")) { $("#sideBar").css("background-color","blue"); } else if ($('#loginBox').is(":hidden")) { $("#sideBar").css("background-color","yellow"); } }); }); </script> ``` So it starts off in its default color (grey by the style sheet) and when mouseenters it loginBox becomes visible and the sideBar turns blue. But when mouseenters again, even though loginBox becomes hidden, the sideBar remains blue. JSFiddle

Original source