Matias Valdiviezo Matias Valdiviezo - 3 months ago 10
Javascript Question

jquery: when click multiple elements then toggle new class

please help with the following problem, i want to create a script that once you had clicked all the skyblue squares, the red square change the class showing green color. Many thanks in advance!!!

Image link

language: lang-js

var mouse = function(){
$('.bt').click(function(){
$(this).toggleClass('bt2');
});
}

var snd = function(){
if ($('#1, #2, #3, #4, #5').hasClass('bt2')){
$('.bt3').toggleClass('live');
}

}

$(document).ready(mouse);
$(document).ready(snd);


language: lang-css

.bt {
width:50px;
height:50px;
background-color:deepskyblue;
display:inline-block;
margin-right:25px;
}

.bt2 {
width:50px;
height:50px;
background-color:orange;
display:inline-block;
margin-right:25px;
}

.bt3 {
width:50px;
height:50px;
background-color:red;
display:inline-block;
margin-right:25px;
}
.live {
width:50px;
height:50px;
background-color:green;
display:inline-block;
margin-right:25px;
}

body {
background-color:#121212;
}


language: lang-html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div id="1" class="bt"></div>
<div id="2" class="bt"></div>
<div id="3" class="bt"></div>
<div id="4" class="bt"></div>
<div id="5" class="bt"></div>
<div id="6" class="bt3"></div>

</div>

Answer

I shortened your version a bit and added the toggling of the live class:

$(document).ready(function() {

  if ($('#1, #2, #3, #4, #5').hasClass('bt2')) {
    $('.bt3').toggleClass('live');
  }

  $('.bt').click(function() {
    $(this).toggleClass('bt2');
     $('.bt3').toggleClass('live', $('.bt:not(.bt2)').length ? false : true );
  });
});

Example

The function toggleClass accepts a second parameter (boolean) which determins wether to remove or add the specified class(es). In this case the state is set via a ternary operator, which checks if there are any elements with the class bt that are not having the class bt2

Is there any specific reason you are assigning the function to variables and use them for the '.ready()' handler?