Hello. I have two div'a , when I div'a on the first one, it changes colors. When you click on the second, it takes the selected color from the first. How can I do that so that when the second block took the color from the first one, then the first one was no longer selected?

Code:

 var colors = ['red', 'blue', 'green', 'yellow']; $(function() { var active_color = 'red'; $('.block-0').click(function() { var color = colors.indexOf(active_color) !== colors.length - 1 ? colors.indexOf(active_color) + 1 : 0; $(this).removeClass('-color-'+active_color).addClass('-color-'+colors[color]); active_color = colors[color]; }); $('.block-1').click(function() { $(this).attr('class', 'block block-1 -color-'+active_color); }); }); 
 .block { display: inline-block; width: 50px; height: 50px; margin: 5px; background-color: black; cursor: pointer; } .-color-red {background-color: red} .-color-blue {background-color: blue} .-color-green {background-color: green} .-color-yellow {background-color: yellow} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="block block-0 -color-red"> </div> <div class="block block-1"> </div> 

    1 answer 1

    For example, use filter () to remove the selected color from the colors array (when clicking on the second block)

     var colors = ['red', 'blue', 'green', 'yellow'], tmp; $(function() { tmp = colors; var active_color = 'red'; $('.block-0').click(function() { var color = colors.indexOf(active_color) !== colors.length - 1 ? colors.indexOf(active_color) + 1 : 0; $(this).removeClass('-color-' + active_color).addClass('-color-' + colors[color]); active_color = colors[color]; }); $('.block-1').click(function() { $(this).attr('class', 'block block-1 -color-' + active_color); colors = tmp; colors = colors.filter(function(c) { return c !== active_color; }); }); }); 
     .block { display: inline-block; width: 50px; height: 50px; margin: 5px; background-color: black; cursor: pointer; } .-color-red { background-color: red } .-color-blue { background-color: blue } .-color-green { background-color: green } .-color-yellow { background-color: yellow } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="block block-0 -color-red"> </div> <div class="block block-1"> </div> 

    • Why doesn't the color come back? - user238739
    • Back in the event that all colors were chosen? Updated the answer. - Alexander Igorevich
    • No, I need, what if the color is not selected, then it was there. And then the colors disappear. Those. needed, just what was selected was not - user238739
    • Thank you ... :) - user238739