A simple plugin that runs a lottery effect with vanilla js.
Check out the demo here.
-
include
lottery-runner.js
(orlottery-runner.min.js
) into your file. -
initiate the
LotteryRunner
with running items' selector and options. -
make sure that
document.querySelectorAll('your_selector').length > 0
or an exception would be thrown.
const lottery = new LotteryRunner('your_selector' [,options]);
lottery.run();
- html markup
<!-- three items for the lottery -->
<div class="item" data-sort="C">Third Item C</div>
<div class="item" data-sort="B">Second Item B</div>
<div class="item" data-sort="A">First Item A</div>
- js
const mylottery = new LotteryRunner('.item', {
orderField: "data-sort", //the order of the items would be item A => item B => item C
startPoint: "C", //the lottery will start from `Item C`,
rounds: 2,
activeClass: "highlighted",
restart: true, //every run will start from `Item C` instead of the last stop point
onRunEnd: function(event) {
console.log(`lottery stops on ${event.detail.stop}`);
}
});
-
orderField |
"data-order"
The attribute that LotteryRunner depends on when sorting items and finding items' index. -
startPoint |
null
The position where lottery starts. Default would start on the first item.
Please use the value of item'sorderField
for this. -
rounds |
3
The rounds that lottery would run before reaching the stop point. -
speed |
100
milliseconds -
restart |
false
Whether start point should reset tostartPoint
after each run. -
activeClass |
"active"
The class name that would be added to the item when active. -
onRunEnd |
null
The function that would be called when a run has ended. The event object would be passed in as the first paramerter whichdetail.stop
returns the stop point of the run.function(event) { // your handler here // event.detail.stop = lottery's stop point // `this` would be the active item (stop point item) }
-
.run([stopPoint])
Start the lottery run effect. IfstopPoint
is not specified, LotteryRunner would generate a random stop point itself.
Use the value of item'sorderField
forstopPoint
.const mylottery = new LotteryRunner('.item'); mylottery.run('B');
<div class="item" data-order="A">item A</div> <div class="item" data-order="B">item B</div> <!-- runner will stop here --> <div class="item" data-order="C">item C</div>
-
.reset()
Reset the start point to the initial optionstartPoint
and remove active class for every items.