kajate
kajate

Reputation: 35

Same random color on multiple pair of divs

So, I have a code where I generate a random color on page load.

$(function() {
        $(".stuff").each(function() {
    var hue = 'rgb('
     + (Math.floor((256)*Math.random()) + 25) + ','
     + (Math.floor((256)*Math.random()) + 25) + ','
     + (Math.floor((256)*Math.random()) + 25) + ')';
    $(this).css("background-color", hue);
    });
});

The color applies to the div .stuff. This div .stuff, works as a button. When I click .stuff, a relating div opens, which I call .filling.

.filling is not displayed on page load. When I click .stuff, both .stuff and .filling is displayed.

I have several .stuff, relating to their each .filling, creating pairs, so to speak.

The html:

<div id="port1Btn" class="divClick stuff">
 </div>
 <div id="port1" class="filling">
     <img src="img/hyper.png">
   </div>

The #port1Btn and #port1 is for defining the content of each pair, connecting them to the right button. And the divClick is for a script that helps close a open .filling when a .stuff is clicked. Here is the code for that, if needed:

$('.divClick').bind("click", showFilling);

function showFilling(event) {
  event.preventDefault();
  var amountOfPorts = 999;
  var ports = "";

  for (i=0;i<amountOfPorts;i++) {
    ports += "#port" + (i+1) +",";
  }
  ports = ports.slice(0, -1);

  $(ports).hide();

  var clickDiv = "#" + event.currentTarget.id;
  var targetDiv = clickDiv.replace('Btn','');

  $(targetDiv).toggle(100);
};

So, what I want to do is to have .stuff and .filling have their same color for each pair, but at the same time, every pair should have a different, random color on page load.

Thank you for reading, hope it was not too long, if so, let me know for future posts.

Upvotes: 0

Views: 94

Answers (1)

TheValyreanGroup
TheValyreanGroup

Reputation: 3599

You can use the next() function.

$(function() {
        $(".stuff").each(function() {
    var hue = 'rgb('
     + (Math.floor((256)*Math.random()) + 25) + ','
     + (Math.floor((256)*Math.random()) + 25) + ','
     + (Math.floor((256)*Math.random()) + 25) + ')';
    $(this).css("background-color", hue);
    $(this).next(".filling").css("background-color",hue);
    });
});

Adding that line will set the next div in the DOM after '.stuff' with the '.filling' class to the same color.

Upvotes: 1

Related Questions