Malasuerte94
Malasuerte94

Reputation: 1474

Randomize li items and freeze multiple

I need to randomize a list of 5-n li items and set for 1-5 items a specific place, for example, I have

  1. a
  2. b
  3. c
  4. d
  5. e
  6. f

And I want to randomize the last 4 and put on li[0] letter D and on li[2] letter F Results:

  1. d
  2. f
  3. c
  4. b
  5. a
  6. e

Here is my code. Where I'm wrong? Thanks!

    var ul = document.querySelector('ul');
    for (var i = ul.children.length; i >= 0; i--) {

    if(ul.children.innerHTML == "XXX") {
        ul.appendChild(ul.children[0]);
    }
    if(ul.children.innerHTML == "XXXX") {
        ul.appendChild(ul.children[1]);
    }
    if(ul.children.innerText == "XX") {
        ul.appendChild(ul.children[2]);
    } else {
        ul.appendChild(ul.children[generateRandom(i) | 0]);
    }
}


function generateRandom(i) {
    var num = Math.random() * i | 0;
    return (num === 0 || num === 1 || num === 2) ? generateRandom(i) : num;
}

Upvotes: 0

Views: 39

Answers (1)

Taplar
Taplar

Reputation: 24965

var $test = $('#test');
var $li = $test.children();

while ($li.length > 0) {
  //pick a random li from the variable
  var $next = $li.eq( Math.floor( Math.random() * 10 * $li.length ) % $li.length );
  //move it to the end of ul
  $test.append($next);
  //remove the li from our variable so it won't be found again
  $li = $li.not($next);
}

//move the f to the top, so when we move the d to the top it will be second
$test.prepend($test.children().filter(function(){ return this.innerHTML === 'f'; }));
//move the d to the top
$test.prepend($test.children().filter(function(){ return this.innerHTML === 'd'; }));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="test">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  <li>e</li>
  <li>f</li>
  <li>g</li>
  <li>h</li>
  <li>i</li>
  <li>j</li>
  <li>k</li>
</ul>

Upvotes: 1

Related Questions