Problem changing a div's background

1

I have the following code

$(".Div2").click(function () {
    $(this).css("background-color","yellow");
  });

It works perfectly for me when I click, it changes to the yellow color, how it could return to the original color when I clicked or double click again.

Any suggestions

Thank you very much.

    
asked by Alexander Quiroz 12.02.2017 в 01:07
source

2 answers

0

You can see that background-color has the div and according to that make a conditional and leave the color as it was, I leave an example:

We can say that the property .css("backgroundColor") will return a string of type:

  

rgb (n, n, n)

$(".Div2").click(function () {
    var currentBackgroundColor = $(this).css("backgroundColor");
    if(currentBackgroundColor == "rgb(255, 255, 0)"){
      $(this).css("background-color","");
    }else {
      $(this).css("background-color","yellow");
    }
    
});
.Div2{
  width: 200px;
  height: 200px;
  border: 1px solid black;
  text-align: center;
  font-family: Arial;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Div2">
DIV 2
</div>
    
answered by 12.02.2017 / 01:54
source
1

You could create a class with the color you need, then add or remove the class according to the event that occurs (click, double click, etc).

Example:

$(document).ready(function() {
  $('div').click(function() {
if($(this).hasClass('selected'))
  $(this).removeClass('selected');
else 
$(this).addClass('selected');
  });
});
div {
  width: 100px;
  height: 50px;
  border: 1px solid black;
}

div.selected {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  Hello
</div>
    
answered by 14.02.2017 в 21:42