Adding multiple .random classes to multiple divs without a duplication

Trying to add a random class to two classes (.left & .right) but with a rule of the two random divs cannot appear at the same time

JS:

$(document).ready(function(){
var classes = ['random-1','random-2', 'random-3']; //add as many classes as u want
var randomnumber = Math.floor(Math.random()*classes.length);

$('.left').addClass(classes[randomnumber]);
});

HTML:

<div class="left">
  Left
</div>

<div class="right">
  Right
</div>


.left {
  background: blue;
  height: 100vh;
  width: 50%;
  float: left;
  position: relative;
}
.right {
  background: red;
  height: 100vh;
  width: 50%;
  float: right;
}

  .random-1 {
     background: orange;
  }
  .random-2 {
     background: yellow;
  }
  .random-3 {
     background: pink;
  }
  .random-4 {
     background: green;
  }
  .random-5 {
     background: blueviolet;
  }

Ideal result would be

<div class="left random-1">
  Left
</div>

<div class="right random-4">
  Right
</div>

https://codepen.io/anon/pen/OOJaqL

Answers 1

  • Add the .random-* class to the left div, only when the right div does not have this class.

    var rightHasClass = $('.right').hasClass(classes[randomnumber]);    
    if( ! rightHasClass){
        $('.left').addClass(classes[randomnumber]);
    }
    
    var leftHasClass = $('.left').hasClass(classes[randomnumber]);
    if( ! leftHasClass){
        $('.right').addClass(classes[randomnumber]);
    }
    

Related Articles