Reputation: 783
I have an enormous list of names that I want in a ul. I only want to display 20 of them at the same time. Ideally, I'd like to fade in and out list items randomly. So, to simplify, we have this list of 10 items:
<ul id="names">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
I know that I could randomize the order like this:
(function($){
$.fn.shuffle = function() {
var allElems = this.get(),
getRandom = function(max) {
return Math.floor(Math.random() * max);
},
shuffled = $.map(allElems, function(){
var random = getRandom(allElems.length),
randEl = $(allElems[random]).clone(true)[0];
allElems.splice(random, 1);
return randEl;
});
this.each(function(i){
$(this).replaceWith($(shuffled[i]));
});
return $(shuffled);
};
})(jQuery);
$(document).ready(function () {
$('#names li').shuffle();
});
The question I have is how can I only display 3 of these list items at once and randomly fade in and out the other individual list items? Also, I want to have each item change randomly on the list item level - not an entirely new UL.
Upvotes: 0
Views: 669
Reputation: 1453
So, I would store all of your names in a JavaScript array, not in html. Only have 3 LI, in your UL, with the same class name or attribute name, or someway of identifying them. Then just have a JavaScript function run on an interval to swap a name in a random LI with a random name from your array, by picking a random index in both, using JavaScript's Math.random() function:
HTML:
<ul>
<li class="randomName">Steve</li>
<li class="randomName">Gary</li>
<li class="randomName">Joan</li>
</ul>
JS:
var names = ['Carlos', 'Khaleel', 'Zach', 'Noah', 'David', 'Nick', 'John', 'Haley', 'Molly', 'Stan', 'Brad', 'Pierre', 'Swati', 'Sarah', 'Steve', 'Gary', 'Joan'];
var lis = document.getElementsByClassName('randomName');
window.setInterval(function changeNameRandomly() {
var randomNamesIndex = Math.floor(Math.random() * names.length);
var randomLiIndex = Math.floor(Math.random() * lis.length);
$(lis[randomLiIndex]).fadeOut("fast", function() {
$(lis[randomLiIndex]).html(names[randomNamesIndex]);
$(lis[randomLiIndex]).fadeIn();
}.bind(this));
}, 3000);
Upvotes: 1