Focus on HTML elements with javascript

1

I have the following code. This code contains 5 divs where when clicking on each one, the one that was clicked receives a value of background.I want that after clicking on one of them, on the next click, the one that was clicked loses the beckground without changing the others.

EX: I clicked the div 1, it became red. I clicked on div 2, it turned red, I clicked on div 1 it lost red color, but 2 has to continue red.

 $(function () {
 
 
 $('.Classe').click(function () {
 
 $(this).css('background','red');
 
 
 });
 
 
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><html><divclass="Classe">valor 1</div>
<div class="Classe">valor 2</div>
<div class="Classe">valor 3</div>
<div class="Classe">valor 4</div>
<div class="Classe">valor 5</div>

<html/>
    
asked by anonymous 18.07.2018 / 19:51

1 answer

1

You can create a class that calls .ativa for example and use the toggleClass method to place and remove the red background when you click.

See the example to understand better. Notice that on the first click I add the class .ativa that has the red background, and on the second click I make toggleClass to remove that class by removing the red from the background.

$(".Classe").click(function(event){
   $(this).toggleClass("ativa");
});
div.ativa {
  background-color: #f00;
}
 
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script><divclass="Classe">valor 1</div>
<div class="Classe">valor 2</div>
<div class="Classe">valor 3</div>
<div class="Classe">valor 4</div>
<div class="Classe">valor 5</div>
    
18.07.2018 / 20:26