Raptorf22 Raptorf22 -4 years ago 63
CSS Question

Setting Event Listener to listen for two clicks before changing background colours of Elements

I'm trying to set up an event listener that will swap the background colours of any 2 divs that are selected. The event listener should only swap the colours once 2 clicked are detected.

For instance, if I have 10 divs on the page, each with different colours in them, when the user clicks on the first div, nothing should happen, but once they click on another div, the event listener should swaps the background colours around.

I'm not sure if it can be done as all the divs have the same class and their starting background colour comes from an array within jquery.

<div class="Sample">
<div class="colourHolder"></div>
<div class="colourHolder"></div>
<div class="colourHolder"></div>
<div class="colourHolder"></div>
<div class="colourHolder"></div>
<div class="colourHolder"></div>
<div class="colourHolder"></div>
<div class="colourHolder"></div>
<div class="colourHolder"></div>
<div class="colourHolder"></div>
</div>





let colors = ['#ff0000', '#0000ff', '#00ff00', '#ffff00', '#ffa500', '#ffc0cb', '#9b30ff', '#ffffff', '#7fffd4', '#000000']

$('.colourHolder').each(function(index, element){
$(element).css("background-color", colors[index]);
})

Answer Source

Is sufficient with an if if else statement and then save the data in vars

let colors = ['#ff0000', '#0000ff', '#00ff00', '#ffff00', '#ffa500', '#ffc0cb', '#9b30ff', '#ffffff', '#7fffd4', '#000000']

$('.colourHolder').each(function(index, element){
  $(element).css("background-color", colors[index]);
});
var prev,
    prevcolor,
    count = 0;
function changeColor(){
  if(count==0){
    prev = $(this);
    prevcolor = prev.css("background-color")
  }else if(count==1){
    prev.css("background-color", $(this).css("background-color"));
    $(this).css("background-color", prevcolor);
    count = -1;
  }
  count+=1;
};
$('.colourHolder').on("click", changeColor)
.colourHolder{width: 100px;height: 100px;display: inline-block}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Sample">
  <div class="colourHolder"></div><div class="colourHolder"></div><div class="colourHolder"></div><div class="colourHolder"></div><div class="colourHolder"></div><div class="colourHolder"></div><div class="colourHolder"></div><div class="colourHolder"></div><div class="colourHolder"></div><div class="colourHolder"></div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download