Nour Ahmed Nour Ahmed - 2 months ago 11
jQuery Question

Change css property depend on if condition with right key press

I'd like to change css property depend on if-condition, what mean if the user press right key change background with specific color and if he press again change background color to other color.



$(document).ready(function() {
$(document).keyup(function(e) {
var counter = 0;
switch (e.which) {
case 39: // right
if (counter == 1) {
$(".my-div").css("background-color", "red");
counter = counter + 1;
}
if (counter == 2) {
$(".my-div").css("background-color", "yellow");
counter = counter + 1;
}
if (counter == 3) {
$(".my-div").css("background-color", "green")
counter = counter + 1;
}
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
console.log(counter);
})

.my-div {
width: 1170px;
height: 500px;
margin: 50px auto;
background-color: #0026ff;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-div"></div>




Answer

Use the stylesheet for background color changes. Here's how you can use the element to keep track of it's current state while controlling styling at the same time:

$(document).ready(function() {

  $(document).keyup(function(e) {
    var counter = $(".my-div").attr('rcount') || 0;

    //Resets to state0. Uncomment to stop after third trigger:
    //if (counter < 3) 
       counter = (++counter % 4);

    switch (e.which) {
      case 39: // right
          $(".my-div").attr("rcount", counter);
          break;
      default:
        return;
    }
    e.preventDefault(); 
  });
})
.my-div.debug {
  width: 200px;
  height: 500px;
  margin: 50px auto;
  background-color: #0026ff;
}

.my-div[rcount='0'] { background-color: #0026ff;}
.my-div[rcount='1'] { background-color: red;}
.my-div[rcount='2'] { background-color: yellow; }
.my-div[rcount='3'] { background-color: green; }

/* Debug styles added to show current rcount value */
.my-div.debug { position:relative; }
.my-div.debug:before { 
  content: 'rcount ' attr( rcount );
  color:white;
  text-shadow:1px 1px 1px black;
  position:absolute;
  left:0;
  top:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-div debug"></div>