'How to give random colors to every post in my post's list
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?
Solution 1:[1]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bender the Greatest |
