Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make every `<li>` with different background colors?

How to make every <li> with different background colors?

<!DOCTYPE html>
<html lang="en">
   <head>
<meta charset="UTF-8">
<title>Title</title>
 </head>
<body>
 <div id="dvi1" class="div1">
    <ul id="ul" class="ul">
      <li>11</li>
      <li>22</li>
      <li>33</li>
      <li>44</li>
   </ul>
</div>
</body>
</html>
like image 766
SCSOName Avatar asked Aug 13 '16 17:08

SCSOName


1 Answers

This is an example where i iterate through all li elements in your document and changing their background color. I predefined colors and after that I'm just using Math.random() to get random color from given array.

$('li').each(function() {
  var back = ["green","blue","gray","yellow","orange","purple","black"];
  var rand = back[Math.floor(Math.random() * back.length)];
  $(this).css('background',rand);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
   <head>
<meta charset="UTF-8">
<title>Title</title>
 </head>
<body>
 <div id="dvi1" class="div1">
    <ul id="ul" class="ul">
      <li>11</li>
      <li>22</li>
      <li>33</li>
      <li>44</li>
   </ul>
</div>
</body>
</html>

EDIT: As requested in comments, i added function which will prevent loop to set same color two times in a row.

var lastPick;
var rand;
$('li').each(function() {
  $(this).css('background',randomColor());
});
function randomColor() {
  var back = ["green","blue","gray","yellow","orange","purple","pink"];
  rand = back[Math.floor(Math.random() * back.length)];
  rand==lastPick?randomColor():rand;
  lastPick = rand;
  return rand;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
   <head>
<meta charset="UTF-8">
<title>Title</title>
 </head>
<body>
 <div id="dvi1" class="div1">
    <ul id="ul" class="ul">
      <li>11</li>
      <li>22</li>
      <li>33</li>
      <li>44</li>
   </ul>
</div>
</body>
</html>
like image 115
Aleksandar Đokić Avatar answered Nov 14 '22 22:11

Aleksandar Đokić