GithubHelp home page GithubHelp logo

josex2r / jquery-slotmachine Goto Github PK

View Code? Open in Web Editor NEW
595.0 35.0 246.0 6.45 MB

Makes Slot Machine effect without jquery (the name is just legacy O_O)

Home Page: http://josex2r.github.io/jQuery-SlotMachine/

License: GNU General Public License v3.0

JavaScript 13.84% CSS 15.34% HTML 23.95% Shell 0.44% TypeScript 46.42%

jquery-slotmachine's Introduction

jQuery-SlotMachine Build Status Dependency Status devDependency Status

📣 jQuery is not neccessary now! The name it's just legacy.

A simple, and lightweight piece of code to make slot machine animation effect. It also exports a js wrapper to allow the usage with jQuery.

To preview what you can do check the example page!

slot-machine

Installation

Install the component using npm:

npm install jquery-slotmachine --save

yarn add jquery-slotmachine

Example

<div id="machine">
  <div>Madrid</div>
  <div>London</div>
  <div>New York</div>
</div>
const el = document.querySelector('#machine');

const machine = new SlotMachine(el, {
  active: 1,
  delay: 450
});

machine.shuffle();

Lookup the sourcecode in the examples page to see more examples.

Usage

Include the script located in dist folder:

<script src="/path/to/slotmachine.min.js"></script>

Or build your own package using a bundled (webpack, rollup, ...)

Then you can make it work calling the lib in your app:

const element = document.getElementById('my-machine');
const machine = new SlotMachine(element, {
  /* options */
});

Settings

Use the first argument of the function to pass an object with the options:

const machine = new SlotMachine(element, {
  active: 2,
  auto: true
});
Name Type Default Description
active Number 0 The initial visible element (0 means the first one)
delay Number 200 Duration (in ms) of each spin
randomize Function () => number Function (returns number) that returns the next active element (random value as default)
direction String up The spin direction (possible values are up and down)

Properties

  • machine.nextActive: Get the next active element (only while shuffling).
  • machine.nextIndex: Next element index according to the current direction.
  • machine.prevIndex: Prev element index according to the current direction.
  • machine.running: Check if the machine is running.
  • machine.stopping: Check if the machine is stopping.
  • machine.active: The current active element.

Methods

machine.shuffle(spins: number): Promise<void>: Starts spining the machine.

Arguments:

  • spins (Number): Optionally set the number of spins until stop.
// Do a single spin
machine.shuffle();
// Do 5 spins before stop
machine.shuffle(5);
// "Infinite" spins
machine.shuffle(Infinity);

machine.stop(spins: number): Promise<void>: Manually stops the machine.

Arguments:

  • spins (Number): Set the number of spins until stop. Use 0 to inmediate stop.
// Start spinning the machine
machine.shuffle(Infinity);
// Do 4 spins an then stop
machine.stop(4);

machine.next(): Promise<void>/machine.prev(): Promise<void>: Spins to the next/previous element.

// Spin to the previous element
machine.prev();

// Spin to the next element
machine.next();

Usefull recipes

To create an inifite carousel effect (as the previous versions run method) use a recursive function:

(async function run() {
  await machine.shuffle(5)
  await timeout(1000);
  run();
})();

Authors

Jose Luis Represa

License

jQuery-SlotMachine is released under the MIT License.

jquery-slotmachine's People

Contributors

jmwohl avatar josex2r avatar next-joserepresa avatar royanon avatar semantic-release-bot avatar unglud avatar yuezk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-slotmachine's Issues

Animation not running smooth when stopping

Hello, I created a lucky draw and I have more than 600 entries at first I used only 10 the animation runs smoothly but when I put the 600 entries so 600 divs the animation was so fast and also time when it goes to stop. Which part I should edit?

onComplete it is getting looped

onComplete event when using shuffle , it is getting looped everytime, for example if i keep alert onComplete function it is getting multiple times

a little question

hi there, i wanted to ask you if its possible to use the plugin for something like changing numbers, so lets say you have 2 divs

<div id="number_1" value="1000"><div>
<div id="number_2" value="2500"><div>

so now when you scroll down the plugin will check the scroll direction and fire machine.next() then spin the number from 1000 > 2500 & same goes when scrolling up, it will fire machine.prev() then spin the number from 2500 > 1000.

Slot machine on 3 rows

Is it possible to create slot machine on 3 rows and the active one to be the middle row,not the top one as it is now?

slotmachine.min.js breaks on Mobile Safari on iOS 9

TypeError: Attempting to change configurable attribute of unconfigurable property.

Inspected by Mac, It's an error when Object.defineProperty is called. I found two Object.defineProperty calls in slotmachine.min.js, but I am not sure the exact reason why this only happens on iOS9.

Device version: iOS 9.3.2

Not working in mobile

the Slotmachine not working in mobile.please guide me...
slotmachinecontainer not working in mobile...but this is work in desktop.

Value

Is there any way to capture the value at which planeMachine stopped?

Example:
I have a TAG (< div > </ div>)

Each div has input its due value, so that slotmachine stops at a particular select I have alert that show the value

alert (document.value ());

my code:

< div id="planeMachine" class="" >

< input type="text" name="fname" value="John"></ div >
< input type="text" name="fname" value="John1">< /div>
< input type="text" name="fname" value="John2">< /div>
</ div >
< button id="slotMachineButtonStop" type="button" class="btn btn-danger btn-lg">Shuffle
< button id="planeMachineStop" type="button" class="btn btn-primary btn-lg">Stop!

< script >
const btnShuffle1 = document.querySelector('#slotMachineButtonStop');
const planeMachine = document.querySelector('#planeMachine');
const btnStop1 = document.querySelector('#planeMachineStop');
const MplaneMachine = new SlotMachine(planeMachine, {
active: 1,
delay: 900,
});
< /script>

< script>
btnShuffle1.addEventListener('click', () => {

MplaneMachine.shuffle(7);
});

btnStop1.addEventListener('click', () => {
MplaneMachine.stop();
});
< /script >

Feature: Responsive Slotmachine

It would be great, if you could add responsive support.
Currently the height of each slot gets calculated by adding up the hight of the elements.
This does not work on a responsive design.
Thanks

Animation improvement

To improve the animation, I recommend using requestAnimationFrame instead of setTimeout. Also to make the animation a bit smoother, animate it via `transform: translateY()?

Using polyfill to make slot machine work with IE

I have noticed that slot machine does not work with IE.

So while I personally feel this is totally ok, because IE is such bad stuff that has hampered web dev for such a long time, there might be cases where IE compatibility maybe important for a project. I am working on such a project recently ...

So I found that using Babel Polyfill (https://babeljs.io/docs/usage/polyfill/) makes slot machine work with IE (tested in IE11 at least).

So maybe this might be worth a hint in the readme.

Only fixed active-slot when showing multiple rows?

Is it possible to get a result, where the active slot is fixed while the next and previous slot is random?
I am using your great plugin on a page, where 3 rows of slots are shown at the same time, but as you can see on the attached image they match on all 3 rows.
screen shot

Lack of simple text example

The documentation would be much more user friendly if you included a single minimal file that just showed a text example

Horizontal Spinner

Hello, I want to horizontally spin the elements. I tried modifying the css but no result.
Can you help me?

Remove selected value from existing array

I'm using the same array to create multiple machines.

How can I achieve the following?
Machine 1 = [1,2,3] (Result is 3, remove it)
Machine 2 = [1,2] (Result is 2, remove it)
Machine 3 = [1]

Right now machine.active gives me the selected index but I have no way to associate this number to my existing array.

Potential Bug?

I prefer the following snippet be written into SlotMachine.prototype.stop instead of SlotMachine.prototype.shuffle

if (this.futureActive === null) {
  //Get random or custom element
  var rnd = this.getCustom();
  this.futureActive = rnd;
}

Don't you think that a destination(futureActive)is better specified in stop function rather than start function since the destination(futureActive) is used to determine where spin should stop at during STOPPING phase?
Suppose a scenario.At beginning, I create an instance of SlotMachine without specify the randomize (like following snippet)

        var machine1 = $("#machine1").slotMachine({
        active  : 0,
        delay   : 500
    });

And I start spinning by evoke machine1.shuffle(). (It should be spinning non-stop)
Then I start do an AJAX request and in callback function, I know a destination at which the spin should stop.
I evoke following sinppet.

             machine1.setRandomize(destinationIndex);
            machine1.stop();  

.
If the first aforementioned snippet was written into SlotMachine.prototype.shuffle, then machine1.setRandomize(destinationIndex) takes no effect.
But instead, I wrote the snippet into SlotMachine.prototype.shuffle, It works effectively and the spin can stop at whichever index given.

Mobile devices stutter animation

Nice work,
I have integrated this into a small project of mine, I am noticing on mobile phone the animation get hung up or freezes. Donyou have any recommendations on how to speed up or smooth the animation for mobile devices?
Thanks

dynamically append elements

First of all thank you for this.. I just want to append few div tags inside slotMachineContainer of machine1 and show that as active index after randomize. Is this possible?

Skip animation feature

I wonder if there is an available function to skip the animation. Like I have to run the slot machine multiple times, but don't want to wait to finish the shuffling.

Isn't jslotmachine.min.js suppose to be slotmachine.min.js?

I was looking at the documentation, and I saw something that was quite confusing:

If you preffer jQuery style then import the wrapper after the jQuery library:

<script src="/path/to/jquery.min.js"></script>
<script src="/path/to/jslotmachine.min.js"></script>
<script src="/path/to/jquery.slotmachine.min.js"></script>

First, "preffer" has a typo and I think:
<script src="/path/to/jslotmachine.min.js"></script>
should be:
<script src="/path/to/slotmachine.min.js"></script>

[Feature request] Typescript definition

Hi,

I'm very exicited with you jQuery-SlotMachine.
Nowaday, typescript is becoming a necessary part of front-end development.

Can you make a typescript definition for your library please?

Thanks,

TypeError: Cannot set property 'overflow' of undefined. at new SlotMachine (slot-machine.js:43)

i don't link to bootstrap's js or css but i have included Jquery .
but when I initialize this SoltMachine ,it throw out an Error.

  • Head
    <link href="assets/animate.css" rel="stylesheet" />
    <link href="assets/slotmachine/jquery.slotmachine.css" rel="stylesheet" />

    <script src="assets/js/jquery.js"></script>
    <script src="assets/jquery.fittext.js"></script>
    <script src="assets/jquery.lettering.js"></script>
    <script src="assets/jquery.textillate.js"></script>

    <script src="assets/slotmachine/slotmachine.js"></script>
    <script src="assets/slotmachine/jquery.slotmachine.js"></script>
  • Body
          <div id="machine1" class="randomizeMachine" style="overflow: hidden;">
                    <div>A</div>
                    <div>B</div>
                    <div>C</div>
                    <div>D</div>
                    <div>E</div>
                    <div>F</div>
                </div>
  • JavaScript (has included jQuery)
        var setting_machine = {
            "machine1": 0,
            "machine2": 0,
            "machine3": 0
        }
        const machine1 = new SlotMachine($("#machine1"), {
            delay: 300,
            auto: true,
            randomize: function () {
                return setting_machine.machine1;
            }
        });

Runtime Error (in Chrome 66.0.3359.181 32bit)

slot-machine.js:43 Uncaught TypeError: Cannot set property 'overflow' of undefined
at new SlotMachine (slot-machine.js:43)
at FM-Table.html:292

In the end, I'm so sorry for my poor English.

Avoiding duplicate images being displayed

Hi, I've just tried this out as a UI for a tool that creates artistic triptychs - three related images placed side-by-side. It's great and has been really quick to get working in 30 minutes over breakfast! I know this sounds counter-intuitive to a slot machine app, but would there be an easy way to use the 'Randomize your machine' example but when an image is picked for #machine1 prevent #machine2 and #machine3 from potentially repeating it. In other words making sure you always have three distinct images? For example could you use the onStopCallback to remove matching elements from the other machines, even whilst it was running? Thanks

Clone slot

I want to show like this: image
How to customize? Plz help. Thanks so much!

simple test for win or loose

Hi,
I'm trying to figure out how to test if the three active element are equal after the shuffle? also is there any simple and clean methode to make it winner after say 3 or 4 times without destroy() ?
thank you :-)

Set Stop Position

Can i set the Stop Position or something?

Its already choosed what a user get, i will only set the position of stopping...

Static Winner number not working.

hi.

I am configuring this slot option according to yourdescription. winnerNumber : [7,7,7], so it's considering 1 as winner number. can you please explain it?

Can we pass parameter for winner. if i will pass array [1,2,3] then slot machine will stop on [1,2,3] and winner should be declared? is that possible?

How to detect win or lose

As title, I want to open a modal to alert user which result their.
How I can get value active for each reel to compare.

Add css to active slot while spinning

If the animation is in effect, is there a css class for the tile in the position that becomes active?

Say mine is 3 tiles tall, as it spins I want the one that will become final, to have different css than surrounding tiles.

tile one - class:notactive
tile two - class:active
tile three -class:notactive

Then as it animates, the tile in the middle always has the class:active.

Cannot figure out how to accomplish this.

Number 6 after 1

Hello,
I really like your work, i found one defect. Sometimes while draw, we get 6 after 1, and it's not elegant :P

Slot Machine displays zeros as results

I have an input field, that determines how many times the slot machine will shuffle, and a button that displays the modal then automatically runs the slot machine.

On the first try, it works fine, but when I close the modal, and run again. all the results are zeros.

this is my sample work

More than one row visible with active on middle

HI there i'm using you plugin on a project and i would like to know how to achieve a functionality similar to this image where we have more than one row visible. In the middle we have the slot that will be randomised and is the active one.

screen shot 2015-03-20 at 01 32 45

ControlPrize / 控制中奖

add code/扩展源码 - jQuery-SlotMachine:
$slot.resetPosition = function(index){
$container.css("margin-top", _getOffset(index));
}

code/调用:

<title>演示:jQuery+SlotMachine插件实现老虎机抽奖</title> <style type="text/css"> .line { padding: 100px 0px;} .slotMachineButton { width: 100px; height: 100px; overflow: hidden; display: inline-block; text-align: center; } .slotMachineButton { -moz-box-shadow: inset 0px 1px 0px 0px #fce2c1; -webkit-box-shadow: inset 0px 1px 0px 0px #fce2c1; box-shadow: inset 0px 1px 0px 0px #fce2c1; background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffc477), color-stop(1, #fb9e25) ); background: -moz-linear-gradient( center top, #ffc477 5%, #fb9e25 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc477', endColorstr='#fb9e25'); background-color: #ffc477; border-radius: 75px; border: 6px solid #eeb44f; display: inline-block; color: #ffffff; font: 700 40px/100px "Microsoft Yahei"; height: 100px; width: 100px; text-decoration: none; text-align: center; text-shadow: 1px 1px 0px #cc9f52; margin-left: 50px; cursor: pointer; } .slotMachineButton:hover { background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #fb9e25), color-stop(1, #ffc477) ); background: -moz-linear-gradient( center top, #fb9e25 5%, #ffc477 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fb9e25', endColorstr='#ffc477'); background-color: #fb9e25; } .slotMachineButton:active { position: relative; top: 1px; } .slotMachine { width: 100px; height: 100px; overflow: hidden; display: inline-block; text-align: center; border: 5px solid #000; background-color: #ffffff; } .noBorder { border: none !important; background: transparent !important; font: 14px arial;} .slotMachine .slot { width: 100px; height: 100px; } .slot1 { background-image: url("img/slot1.png"); } .slot2 { background-image: url("img/slot2.png"); } .slot3 { background-image: url("img/slot3.png"); } .slot4 { background-image: url("img/slot4.png"); } .slot5 { background-image: url("img/slot5.png"); } .slot6 { background-image: url("img/slot6.png"); } </style>
<div class="demo">
    <h3>
        <a href="index.html" class="cur">演示1:简单效果</a> 
    </h3>
    <div class="line">
        <div class="content" style="text-align: center">
            <div class="clear">
                <div id="machine1" class="slotMachine">
                    <div class="slot slot1"></div>
                    <div class="slot slot2"></div>
                    <div class="slot slot3"></div>
                    <div class="slot slot4"></div>
                    <div class="slot slot5"></div>
                    <div class="slot slot6"></div>
                </div>
                <div id="machine2" class="slotMachine">
                    <div class="slot slot1"></div>
                    <div class="slot slot2"></div>
                    <div class="slot slot3"></div>
                    <div class="slot slot4"></div>
                    <div class="slot slot5"></div>
                    <div class="slot slot6"></div>
                </div>
                <div id="machine3" class="slotMachine">
                    <div class="slot slot1"></div>
                    <div class="slot slot2"></div>
                    <div class="slot slot3"></div>
                    <div class="slot slot4"></div>
                    <div class="slot slot5"></div>
                    <div class="slot slot6"></div>
                </div>
                <div id="slotMachineButton1" class="slotMachineButton">GO!</div>
            </div>
            <div class="clear">
                <div id="machine1Result" class="slotMachine noBorder" style="text-align:left"></div>
                <div id="machine2Result" class="slotMachine noBorder" style="text-align:left"></div>
                <div id="machine3Result" class="slotMachine noBorder" style="text-align:left"></div>
                <div class="slotMachine noBorder"></div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery.slotmachine.js"></script> <script type="text/javascript"> $(function() { var machine1 =window.machine1 = $("#machine1").slotMachine({ //第一个老虎机设置 active: 0, //初始化时显示第几张图案 delay: 500 //延迟 }); var machine2 = $("#machine2").slotMachine({ active: 1, delay: 500 }); var machine3 = $("#machine3").slotMachine({ active: 2, delay: 500 }); $("#slotMachineButton1").click(function() { //开始抽奖 machine1.shuffle(1, function(){ machine1.resetPosition(1) }); setTimeout(function() { //500秒后调用第二个老虎机 machine2.shuffle(1, function(){ machine2.resetPosition(1) }); }, 500); setTimeout(function() { //1000秒后调用第三个老虎机 machine3.shuffle(1, function(){ machine3.resetPosition(1) }); }, 1000); }) }); </script>

Mutliple Stop Attempts

Hello,

i found a bug in the stop() method where you are able to trigger mutliple stop attempts and overwrite the "futureActive" resulting in a null value.

jquery.slotmachine.js:448: this.isRunning = true;

Solution:
The value of isRunning of the above line should be set to false to prevent reentering the stop method through the guard at the beginning of stop().

Cheers,
Bastian

Slot Machine - Help

Hello sir,

Good day. At start i need 1 Logo for all the 3 Slot.

final slot result

Slot 1 - 1
Slot 2 -24
Slot 3 -48

for all the time i want the same result.

Can you Please help me.

Update randomizer by AJAX

I needed a way to set the randomizer return value after each spin via AJAX (I'm using PHP to prevent client side injection). I was able to add a new function that accepts the index of the chosen element... maybe there's a better way but here's a snippet of my solution.

/**
  * @desc PRIVATE - Updates the index to the new custom value
*/
function _updateCustom(indexToSet){
    _active.index = indexToSet;
}


/**
 * @desc PUBLIC - SET chosen element
*/
setCustom : function(indexToSet){
    if(typeof indexToSet==='number' && indexToSet>=0 && indexToSet<$titles.length){
        _updateCustom(indexToSet);
    }
}

Then I did something really bad with the _getCustom() private function:
I changed var index = self.settings.randomize(_active.index); to just var index = _active.index;

And then my usage was simply:

$("#pull").click(function() {
  $.ajax({
    url: 'ajax/slotmachine_ajax_responder.php',
    type: 'POST',
    data: {'method': "spin"},
    dataType: 'json',
    cache: false,
    success: function(data) {
        if (data.success) {
            //Set finishing placements
            machine1.setCustom(data.num1);
            machine2.setCustom(data.num2);
            machine3.setCustom(data.num3);

            //Do the spinning
            machine1.shuffle(3, onComplete);

            setTimeout(function() {
                machine2.shuffle(3, onComplete);
            }, 250);

            setTimeout(function() {
                machine3.shuffle(3, onComplete);
            }, 500);
        }
    }
  });
});

Please let me know where I can improve on this. Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.