Focus on HTML Elements with javascript

Asked

Viewed 82 times

1

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

EX.:I clicked on div 1 ,turned red. I clicked on div 2 ,turned red,I clicked on div 1 lost the red color ,but 2 must 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>

<div class="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/>

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 clicking.

See the example to better understand. Note that in the first click I add the class .ativa which has the red background, and the second click I do the toggleClass to remove this class thus 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>

<div class="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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.