0

Here is my code:

{% for post in post_list %}
<div class="mybox">

  <div id="post">
    <h1 ><a class = 'title_font' href="{% url 'blog:post_detail' pk=post.pk %}"><strong>{{ post.title }}</strong></a></h1>

    <a href="{%url 'blog:post_detail' pk=post.pk %}">Comments :</a>
  </div>

</div>
<script src='{% static 'js/blog.js' %}'></script>
{% endfor %}

In my blog.js JavaScript file, when I assign mybox random colors, all the posts have the same random background-color.

How can I get different colors for each .mybox element?

Roy
  • 7,811
  • 4
  • 24
  • 47
  • Please post the content of `blog.js` to help you fix it. In general you could use a `each` method on the `.mybox` selector and assign a new random value – Andrea Olivato Jun 27 '21 at 10:57
  • Hi, could you explain what 'assign mybox random colors' ? It looks as though mybox is just a class so it would have just one background-color. – A Haworth Jun 27 '21 at 13:00
  • I guess this is what you are looking for [Check this out](https://stackoverflow.com/questions/5850590/random-color-generator-with-hue-saturation-and-more-controls) – user1501365 Jun 27 '21 at 19:00

1 Answers1

0

const randomNumber = (min, max) =>
  Math.floor(Math.random() * (max - min + 1) + min);

const randomColor = () =>
  `rgb(${randomNumber(0, 255)}, ${randomNumber(0, 255)}, ${randomNumber(
    0,
    255
  )})`;

const btn = document.querySelector('.btn');

const assignRandom = () => {
  btn.style.color = randomColor();
  btn.style.backgroundColor = randomColor();
};

assignRandom();
setInterval(assignRandom, 1000);
.btn {
  display: inline-block;
  font-size: 20px;
  font-family: inherit;
  font-weight: 500;
  border: none;
  padding: 10px 20px;
  border-radius: 10rem;
  cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">

<head>

  <body><button class="btn">Look how the colors are changing</button>
  </body>
</head>

</html>
codewario
  • 19,553
  • 20
  • 90
  • 159
Tarun Dadlani
  • 152
  • 3
  • 10