I like to display some numbers as pictures. All numbers are included in one picture.
I started with creating a span for each number and each span get a different class so that I can change the picture for the correct number with the style attribute "background-position".
This is working for me. But now I like to add a little animation to this numbers like count up to the correct value. I can do this for one span (number) but how can I do this for all numbers?
HTML:
<style>
.digit0 { background-position: 0 0; }
.digit1 { background-position: 0 -120px; }
.digit2 { background-position: 0 -240px; }
.digit3 { background-position: 0 -360px; }
.digit4 { background-position: 0 -480px; }
.digit5 { background-position: 0 -600px; }
.digit6 { background-position: 0 -720px; }
.digit7 { background-position: 0 -840px; }
.digit8 { background-position: 0 -960px; }
.digit9 { background-position: 0 -1080px; }
</style>
</head>
<body>
<h1>Examples</h1>
<p>
<div id="number">here</div>
</p>
</body>
Javascript:
<script type="text/javascript">
$(document).ready(function(){
// Your code here
var dd = "5487";
dd = dd.replace(/(\d)/g, '<span class="digit0" id="count$1" style="display: inline-block; height: 20px; line-height: 40px; width: 14px; vertical-align: middle; text-align: center; font: 0/0 a; text-shadow: none; background-image: url(../src/jquery.counter-analog.png); color: transparent; margin: 0;"></span>');
$("#number").html(dd);
count = $("#count4").attr("id").replace("count", "").toString();
var i = 0;
setInterval(function() {
counter();
}, 100);
function counter() {
if(i < count) {
i++;
$("#count4").attr("class", "digit" + i + "");
}
}
});
</script>
This is not possible using pure Javascript.
What you're asking for will have to be performed server-side using something like PHP's GD.
Here's one way to do it. It certainly still has room for efficiency and legibility improvement, here and there (see edit history of this answer for one such improvement :) ). But it's a decent start imho:
// goal digits
var dd = '5487';
// separate digits
var digits = dd.split( '' );
// set some animation interval
var interval = 100;
// create spans for each digit,
// append to div#number and initialize animation
digits.forEach( function( value, index ) {
// create a span with initial conditions
var span = $( '<span>', {
'class': 'digit0',
'data': {
'current': 0,
'goal' : value
}
} );
// append span to the div#number
span.appendTo( $( 'div#number' ) );
// call countUp after interval multiplied by the index of this span
setTimeout( function() { countUp.call( span ); }, index * interval );
} );
// count animation function
function countUp()
{
// the current span we're dealing with
var span = this;
// the current value of the span
var current = span.data( 'current' );
// the end goal digit of this span
var goal = span.data( 'goal' );
// increment the digit, if we've not reached the goal yet
if( current < goal )
{
++current;
span.attr( 'class', 'digit' + current );
span.data( 'current', current );
// call countUp again after interval
setTimeout( function() { countUp.call( span ); }, interval );
}
}
See it in action on jsfiddle
To change the speed of the animation, alter the value of interval.
I've answered another similar question some days ago:
$.fn.increment = function (from, to, duration, easing, complete) {
var params = $.speed(duration, easing, complete);
return this.each(function(){
var self = this;
params.step = function(now) {
self.innerText = now << 0;
};
$({number: from}).animate({number: to}, params);
});
};
$('#count').increment(0, 1337);
Update
If you really want to use images, take this:
$.fn.increment = function (x, y, from, to, duration, easing, complete) {
var params = $.speed(duration, easing, complete);
return this.each(function(){
var self = this;
params.step = function(now) {
self.style.backgroundPosition = x * Math.round(now) + 'px ' + y * Math.round(now) + 'px';
};
$({number: from}).animate({number: to}, params);
});
};
$('#count').increment(0, 120, 9);
Related
I have this jquery functions. I want to make it just one function so I can get thesame results by just calling a function and passing some arguements.
As you can see, the function does basically the same thing counting numbers. I would love to just have one function , then parse out arguments to get the same results. something like startcount(arg1, arg2);
var one_countsArray = [2,4,6,7,4252];
var two_countsArray = [3,3,4,7,1229];
var sumemp = one_countsArray.reduce(add, 0);
var sumallis = two_countsArray.reduce(add, 0);
function add(a, b) {
return a + b;
}
var count = 0;
var inTv = setInterval(function(){startCount()},100);
var inTv2 = setInterval(function(){startCount2()},100);
function startCount()
{
if(count == sumemp) {
clearInterval(inTv);
} else {
count++;
}
$('.stats_em').text(count);
}
var count2 = 10;
function startCount2()
{
if(count2 == sumallis) {
clearInterval(inTv2);
} else {
count2++;
}
$('.stats_iss').text(count2);
}
div {
padding:50px 0;
background: #000000;
color: #ffffff;
width: 100px;
height:100px;
border-radius:50%;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="stats_em"></div>
<div class="stats_iss"></div>
How about a very simple jquery plugin
$.fn.countTo = function(arrNums){
var self = this;
function add(a,b){
return a+b;
}
var current = 0;
var max = arrNums.reduce(add,0);
var int = setInterval(function(){
if(current == max)
clearInterval(int);
else
current++;
self.text(current);
},100);
return this;
}
$('.stats_em').countTo([2,4,6,7,4252]);
$('.stats_iss').countTo([3,3,4,7,1229]);
div {
padding:50px 0;
background: #000000;
color: #ffffff;
width: 100px;
height:100px;
border-radius:50%;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="stats_em"></div>
<div class="stats_iss"></div>
When you notice you're rewriting chunks of similar code, moving to one generic function is the right approach! The best way to start is by trying to determine what you're parameters would be:
count and count2 show that you need a start count for your timer to start at
sumemp and sumpallis show that you need to be able to specify a maximum count
inTv and inTv show that you need to be able to set the interval
$('.stats_iss') and $('.stats_em') show that you need to be able to determine the output element
This means your final class, function or jquery extension will at least have a signature that resembles this:
function(startCount, maximumCount, interval, outputElement) { }
Once you've written this, you can paste in the code you already have. (I've replaced your setInterval with a setTimeout, other than that, not much changed)
var createCounter = function(start, max, interval, outputElement) {
var count = start;
var timeout;
var start = function() {
count += 1;
outputElement.text(count);
if (count < max) {
timeout = setTimeout(start, interval);
}
}
var stop = clearTimeout(timeout);
return {
start: start,
stop: stop
}
}
var one_countsArray = [2, 4, 6, 7, 300];
var two_countsArray = [3, 3, 4, 7, 100];
var sumemp = one_countsArray.reduce(add, 0);
var sumallis = two_countsArray.reduce(add, 0);
function add(a, b) {
return a + b;
}
var counters = [
createCounter(0, sumemp, 100, $('.stats_em')),
createCounter(10, sumallis, 100, $('.stats_iss'))
];
counters.forEach(function(counter) {
counter.start();
});
div {
padding: 50px 0;
background: #000000;
color: #ffffff;
width: 100px;
height: 100px;
border-radius: 50%;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="stats_em"></div>
<div class="stats_iss"></div>
I hope you understand my problem.
At the moment I have a JS-function that choses randomly a div of a specific Html-Class.
Now i would like to rewrite the function that it picks one div after the other, just like they are ordered in the HTML-content.
How can I do this?
For information: the random selection is made with jquery and looks like this:
function pickrandom() {
var elems = $(".classname");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
console.log(keep);
$(elems[keep]).click();
}
}
Thanks
$(document).on('click', '.classname', function(){
var self = $(this);
var total_items = $('.classname').length; // 10
var index = self.index(); //2 for 3rd element
if (index < total_items) {
setTimeout(function () {
$('.classname').eq(index+1).trigger('click');
}, 3000);
}
});
this will call the next clicks in 3 sec interval
i don't know why you are using a randomizer function.you can allow the user to make that click
Hopefully this helps you - can't see your markup, but it should get you on the right track. I've also changed your .click() to a .trigger('click') which should be quite a bit more dependable.
JavaScript
function pickrandom() {
var elems = $(".classname");
if (elems.length) {
var curTarget = Math.floor(Math.random() * elems.length);
console.log(curTarget);
$(elems[curTarget]).trigger('click');
// Find index of our next target - if we've reached
// the end, go back to beginning
var nextTarget = curTarget + 1;
if( nextTarget > elems.length ) {
nextTarget = 0;
}
// Wait 3 seconds and click the next div
setTimeout( function() { $(elems[nextTarget]).trigger('click'); }, 3000 );
}
}
$("div").click(function() {
var el = $(this);
setTimeout(function() {
console.log(el.text());
el.toggleClass("click");
}, 2000);
});
var random = Math.floor((Math.random() * $("div").length) + 1);
var index = random - 1;
console.log("Random number: ", random);
var clicker = setInterval(function() {
if (index === $("div").length) {
clearInterval(clicker);
console.log("cleared interval");
} else {
$("div").eq(index).click();
index++;
}
}, 2000)
div {
height: 50px;
width: 100%;
border: 2px solid black;
background-color: lightgreen;
margin-bottom: 10px;
text-align: center;
font-size: 30px;
}
.click {
background-color: lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Div 1
</div>
<div>
Div 2
</div>
<div>
Div 3
</div>
<div>
Div 4
</div>
<div>
Div 5
</div>
<div>
Div 6
</div>
I created a sliding puzzle with different formats like: 3x3, 3x4, 4x3 and 4x4. When you run my code you can see on the right side a selection box where you can choose the 4 formats. The slidingpuzzle is almost done. But I need a function which checks after every move if the puzzle is solved and if that is the case it should give out a line like "Congrantulations you solved it!" or "You won!". Any idea how to make that work?
In the javascript code you can see the first function loadFunc() is to replace every piece with the blank one and the functions after that are to select a format and change the format into it. The function Shiftpuzzlepieces makes it so that you can move each piece into the blank space. Function shuffle randomizes every pieces position. If you have any more question or understanding issues just feel free to ask in the comments. Many thanks in advance.
Since I don't have enough reputation I will post a link to the images here: http://imgur.com/a/2nMlt . These images are just placeholders right now.
Here is the jsfiddle:
http://jsfiddle.net/Cuttingtheaces/vkyxgwo6/19/
As always, there is a "hacky", easy way to do this, and then there is more elegant but one that requires significant changes to your code.
Hacky way
To accomplish this as fast and dirty as possible, I would go with parsing id-s of pieces to check if they are in correct order, because they have this handy pattern "position" + it's expected index or "blank":
function isFinished() {
var puzzleEl = document.getElementById('slidingpuzzleContainer').children[0];
// convert a live list of child elements into regular array
var pieces = [].slice.call(puzzleEl.children);
return pieces
.map(function (piece) {
return piece.id.substr(8); // strip "position" prefix
})
.every(function (id, index, arr) {
if (arr.length - 1 == index) {
// last peace, check if it's blank
return id == "blank";
}
// check that every piece has an index that matches its expected position
return index == parseInt(id);
});
}
Now we need to check it somewhere, and naturally the best place would be after each move, so shiftPuzzlepieces() should be updated to call isFinished() function, and show the finishing message if it returns true:
function shiftPuzzlepieces(el) {
// ...
if (isFinished()) {
alert("You won!");
}
}
And voilà: live version.
How would I implement this game
For me, the proper way of implementing this would be to track current positions of pieces in some data structure and check it in similar way, but without traversing DOM or checking node's id-s. Also, it would allow to implement something like React.js application: onclick handler would mutate current game's state and then just render it into the DOM.
Here how I would implement the game:
/**
* Provides an initial state of the game
* with default size 4x4
*/
function initialState() {
return {
x: 4,
y: 4,
started: false,
finished: false
};
}
/**
* Inits a game
*/
function initGame() {
var gameContainer = document.querySelector("#slidingpuzzleContainer");
var gameState = initialState();
initFormatControl(gameContainer, gameState);
initGameControls(gameContainer, gameState);
// kick-off rendering
render(gameContainer, gameState);
}
/**
* Handles clicks on the container element
*/
function initGameControls(gameContainer, gameState) {
gameContainer.addEventListener("click", function hanldeClick(event) {
if (!gameState.started || gameState.finished) {
// game didn't started yet or already finished, ignore clicks
return;
}
if (event.target.className.indexOf("piece") == -1) {
// click somewhere not on the piece (like, margins between them)
return;
}
// try to move piece somewhere
movePiece(gameState, parseInt(event.target.dataset.index));
// check if we're done here
checkFinish(gameState);
// render the state of game
render(gameContainer, gameState);
event.stopPropagation();
return false;
});
}
/**
* Checks whether game is finished
*/
function checkFinish(gameState) {
gameState.finished = gameState.pieces.every(function(id, index, arr) {
if (arr.length - 1 == index) {
// last peace, check if it's blank
return id == "blank";
}
// check that every piece has an index that matches its expected position
return index == id;
});
}
/**
* Moves target piece around if there's blank somewhere near it
*/
function movePiece(gameState, targetIndex) {
if (isBlank(targetIndex)) {
// ignore clicks on the "blank" piece
return;
}
var blankPiece = findBlankAround();
if (blankPiece == null) {
// nowhere to go :(
return;
}
swap(targetIndex, blankPiece);
function findBlankAround() {
var up = targetIndex - gameState.x;
if (targetIndex >= gameState.x && isBlank(up)) {
return up;
}
var down = targetIndex + gameState.x;
if (targetIndex < ((gameState.y - 1) * gameState.x) && isBlank(down)) {
return down;
}
var left = targetIndex - 1;
if ((targetIndex % gameState.x) > 0 && isBlank(left)) {
return left;
}
var right = targetIndex + 1;
if ((targetIndex % gameState.x) < (gameState.x - 1) && isBlank(right)) {
return right;
}
}
function isBlank(index) {
return gameState.pieces[index] == "blank";
}
function swap(i1, i2) {
var t = gameState.pieces[i1];
gameState.pieces[i1] = gameState.pieces[i2];
gameState.pieces[i2] = t;
}
}
/**
* Handles form for selecting and starting the game
*/
function initFormatControl(gameContainer, state) {
var formatContainer = document.querySelector("#formatContainer");
var formatSelect = formatContainer.querySelector("select");
var formatApply = formatContainer.querySelector("button");
formatSelect.addEventListener("change", function(event) {
formatApply.disabled = false;
});
formatContainer.addEventListener("submit", function(event) {
var rawValue = event.target.format.value;
var value = rawValue.split("x");
// update state
state.x = parseInt(value[0], 10);
state.y = parseInt(value[1], 10);
state.started = true;
state.pieces = generatePuzzle(state.x * state.y);
// render game
render(gameContainer, state);
event.preventDefault();
return false;
});
}
/**
* Renders game's state into container element
*/
function render(container, state) {
var numberOfPieces = state.x * state.y;
updateClass(container, state.x, state.y);
clear(container);
var containerHTML = "";
if (!state.started) {
for (var i = 0; i < numberOfPieces; i++) {
containerHTML += renderPiece("", i) + "\n";
}
} else if (state.finished) {
containerHTML = "<div class='congratulation'><h2 >You won!</h2><p>Press 'Play!' to start again.</p></div>";
} else {
containerHTML = state.pieces.map(renderPiece).join("\n");
}
container.innerHTML = containerHTML;
function renderPiece(id, index) {
return "<div class='piece' data-index='" + index + "'>" + id + "</div>";
}
function updateClass(container, x, y) {
container.className = "slidingpuzzleContainer" + x + "x" + y;
}
function clear(container) {
container.innerHTML = "";
}
}
/**
* Generates a shuffled array of id-s ready to be rendered
*/
function generatePuzzle(n) {
var pieces = ["blank"];
for (var i = 0; i < n - 1; i++) {
pieces.push(i);
}
return shuffleArray(pieces);
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
}
body {
font-family: "Lucida Grande", "Lucida Sans Unicode", Verdana, Helvetica, Arial, sans-serif;
font-size: 12px;
color: #000;
}
#formatContainer {
position: absolute;
top: 50px;
left: 500px;
}
#formatContainer label {
display: inline-block;
max-width: 100%;
margin-bottom: 5px;
}
#formatContainer select {
display: block;
width: 100%;
margin-top: 10px;
margin-bottom: 10px;
}
#formatContainer button {
display: inline-block;
width: 100%;
}
.piece {
width: 96px;
height: 96px;
margin: 1px;
float: left;
border: 1px solid black;
}
.slidingpuzzleContainer3x3,
.slidingpuzzleContainer3x4,
.slidingpuzzleContainer4x3,
.slidingpuzzleContainer4x4 {
position: absolute;
top: 50px;
left: 50px;
border: 10px solid black;
}
.slidingpuzzleContainer3x3 {
width: 300px;
height: 300px;
}
.slidingpuzzleContainer3x4 {
width: 300px;
height: 400px;
}
.slidingpuzzleContainer4x3 {
width: 400px;
height: 300px;
}
.slidingpuzzleContainer4x4 {
width: 400px;
height: 400px;
}
.congratulation {
margin: 10px;
}
}
<body onload="initGame();">
<div id="slidingpuzzleContainer"></div>
<form id="formatContainer">
<label for="format">select format:</label>
<select name="format" id="format" size="1">
<option value="" selected="true" disabled="true"></option>
<option value="3x3">Format 3 x 3</option>
<option value="3x4">Format 3 x 4</option>
<option value="4x3">Format 4 x 3</option>
<option value="4x4">Format 4 x 4</option>
</select>
<button type="submit" disabled="true">Play!</button>
</form>
</body>
Here we have the initGame() function that starts everything. When called it will create an initial state of the game (we have default size and state properties to care about there), add listeners on the controls and call render() function with the current state.
initGameControls() sets up a listener for clicks on the field that will 1) call movePiece() which will try to move clicked piece on the blank spot if the former is somewhere around, 2) check if after move game is finished with checkFinish(), 3) call render() with updated state.
Now render() is a pretty simple function: it just gets the state and updates the DOM on the page accordingly.
Utility function initFormatControl() handles clicks and updates on the form for field size selection, and when the 'Play!' button is pressed will generate initial order of the pieces on the field and call render() with new state.
The main benefit of this approach is that almost all functions are decoupled from one another: you can tweak logic for finding blank space around target piece, to allow, for example, to swap pieces with adjacent ids, and even then functions for rendering, initialization and click handling will stay the same.
$(document).on('click','.puzzlepiece', function(){
var count = 0;
var imgarray = [];
var test =[0,1,2,3,4,5,6,7,8,'blank']
$('#slidingpuzzleContainer img').each(function(i){
var imgalt = $(this).attr('alt');
imgarray[i] = imgalt;
count++;
});
var is_same = (imgarray.length == test.length) && imgarray.every(function(element, index) {
return element === array2[index];
});
console.log(is_same); ///it will true if two array is same
});
try this... this is for only 3*3.. you pass the parameter and makethe array value as dynamically..
I am trying to create a slot machine using the following jquery plugin: jquery slot machine
I started with the simple Demo und entered my own list. The Problem I am having is that I need more than just that block which shows 1 line of the list. I need to show what is above and beneath the middle line of the lists. So I made the jSlotsWrapper box bigger.
Now I have the problem that when the lists spin, at the end of the list you see empty space. How can I make that the list has no end? So where the last item in the list is, I want to start again with the list.
EDIT
here is my html file
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Datengut Spielautomat</title>
<style type="text/css">
body {
text-align: center;
position: absolute;
height: 600px;
margin: auto;
top: 0; left: 0; bottom: 0; right: 0;
}
ul {
padding: 0;
margin: 0;
list-style: none;
}
li {
height: 62px;
}
.jSlots-wrapper {
overflow: hidden;
text-align: center;
font-family:arial,helvetica,sans-serif;
font-size: 40px;
text-shadow: 2px 2px 2px #888888;
height: 600px;
width: 1242px;
margin: 10px auto;
border: 2px solid;
border-color: #ffa500;
box-shadow: 5px 5px 5px #888888;
box-shadow: inset 0 200px 100px -100px #555555, inset 0 -200px 100px -100px #555555;
}
.jSlots-wrapper::after {
content: "";
background:url("blumen.jpg");
opacity: 0.5;
z-index: -1;
}
.slot {
z-index: -1;
width: 410px;
text-align: center;
margin-left: 5px auto;
margin-right: 5px auto;
float: left;
border-left: 2px solid;
border-right: 2px solid;
border-color: #ffa500;
}
.line {
width: 410px;
height: 2px;
-webkit-transform:
translateY(-20px)
translateX(5px)
}
</style>
</head>
<body>
<ul class="slot">
<li>Bauakte</li>
<li></li>
<li>Bautagebuch</li>
<li></li>
<li>Mängelverwaltung</li>
<li></li>
<li>Störungsverwaltung</li>
<li></li>
<li>Personalakte</li>
<li></li>
<li>Maschinenakte</li>
<li></li>
</ul>
<script src="jquery.1.6.4.min.js" type="text/javascript" charset="utf-8"></script>
<script src="jquery.easing.1.3.js" type="text/javascript" charset="utf-8"></script>
<script src="jquery.jSlots.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
// normal example
$('.slot').jSlots({
number : 3,
spinner : 'body',
spinEvent : 'keypress',
easing: 'easeOutSine',
time : 7000,
loops : 6,
});
</script>
</body>
</html>
and here is my js file:
(function($){
$.jSlots = function(el, options){
var base = this;
base.$el = $(el);
base.el = el;
base.$el.data("jSlots", base);
base.init = function() {
base.options = $.extend({},$.jSlots.defaultOptions, options);
base.setup();
base.bindEvents();
};
// --------------------------------------------------------------------- //
// DEFAULT OPTIONS
// --------------------------------------------------------------------- //
$.jSlots.defaultOptions = {
number : 3, // Number: number of slots
winnerNumber : 1, // Number or Array: list item number(s) upon which to trigger a win, 1-based index, NOT ZERO-BASED
spinner : '', // CSS Selector: element to bind the start event to
spinEvent : 'click', // String: event to start slots on this event
onStart : $.noop, // Function: runs on spin start,
onEnd : $.noop, // Function: run on spin end. It is passed (finalNumbers:Array). finalNumbers gives the index of the li each slot stopped on in order.
onWin : $.noop, // Function: run on winning number. It is passed (winCount:Number, winners:Array)
easing : 'swing', // String: easing type for final spin
time : 7000, // Number: total time of spin animation
loops : 6 // Number: times it will spin during the animation
};
// --------------------------------------------------------------------- //
// HELPERS
// --------------------------------------------------------------------- //
base.randomRange = function(low, high) {
return Math.floor( Math.random() * (1 + high - low) ) + low;
};
// --------------------------------------------------------------------- //
// VARS
// --------------------------------------------------------------------- //
base.isSpinning = false;
base.spinSpeed = 0;
base.winCount = 0;
base.doneCount = 0;
base.$liHeight = 0;
base.$liWidth = 0;
base.winners = [];
base.allSlots = [];
// --------------------------------------------------------------------- //
// FUNCTIONS
// --------------------------------------------------------------------- //
base.setup = function() {
// set sizes
var $list = base.$el;
var $li = $list.find('li').first();
base.$liHeight = $li.outerHeight();
base.$liWidth = $li.outerWidth();
base.liCount = base.$el.children().length;
base.listHeight = base.$liHeight * base.liCount;
base.increment = (base.options.time / base.options.loops) / base.options.loops;
$list.css('position', 'relative');
$li.clone().appendTo($list);
base.$wrapper = $list.wrap('<div class="jSlots-wrapper"></div>').parent();
// remove original, so it can be recreated as a Slot
base.$el.remove();
// clone lists
for (var i = base.options.number - 1; i >= 0; i--){
base.allSlots.push( new base.Slot() );
}
};
base.bindEvents = function() {
$(base.options.spinner).bind(base.options.spinEvent, function(event) {
if (event.which == 32) {
if (!base.isSpinning) {
base.playSlots();
}
}
});
};
// Slot constructor
base.Slot = function() {
this.spinSpeed = 0;
this.el = base.$el.clone().appendTo(base.$wrapper)[0];
this.$el = $(this.el);
this.loopCount = 0;
this.number = 0;
};
base.Slot.prototype = {
// do one rotation
spinEm : function() {
var that = this;
that.$el
.css( 'top', -base.listHeight )
.animate( { 'top' : '0px' }, that.spinSpeed, 'linear', function() {
that.lowerSpeed();
});
},
lowerSpeed : function() {
this.spinSpeed += base.increment;
this.loopCount++;
if ( this.loopCount < base.options.loops ) {
this.spinEm();
} else {
this.finish();
}
},
// final rotation
finish : function() {
var that = this;
var endNum = base.randomRange( 1, base.liCount );
while (endNum % 2 == 0) {
endNum = base.randomRange( 1, base.liCount );
}
var finalPos = - ( (base.$liHeight * endNum) - base.$liHeight );
var finalSpeed = ( (this.spinSpeed * 0.5) * (base.liCount) ) / endNum;
that.$el
.css( 'top', -base.listHeight )
.animate( {'top': finalPos}, finalSpeed, base.options.easing, function() {
base.checkWinner(endNum, that);
});
}
};
base.checkWinner = function(endNum, slot) {
base.doneCount++;
// set the slot number to whatever it ended on
slot.number = endNum;
// if its in the winners array
if (
( $.isArray( base.options.winnerNumber ) && base.options.winnerNumber.indexOf(endNum) > -1 ) ||
endNum === base.options.winnerNumber
) {
// its a winner!
base.winCount++;
base.winners.push(slot.$el);
}
if (base.doneCount === base.options.number) {
var finalNumbers = [];
$.each(base.allSlots, function(index, val) {
finalNumbers[index] = val.number;
});
if ( $.isFunction( base.options.onEnd ) ) {
base.options.onEnd(finalNumbers);
}
if ( base.winCount && $.isFunction(base.options.onWin) ) {
base.options.onWin(base.winCount, base.winners, finalNumbers);
}
base.isSpinning = false;
}
};
base.playSlots = function() {
base.isSpinning = true;
base.winCount = 0;
base.doneCount = 0;
base.winners = [];
if ( $.isFunction(base.options.onStart) ) {
base.options.onStart();
}
$.each(base.allSlots, function(index, val) {
this.spinSpeed = 250*index;
this.loopCount = 0;
this.spinEm();
});
};
base.onWin = function() {
if ( $.isFunction(base.options.onWin) ) {
base.options.onWin();
}
};
// Run initializer
base.init();
};
// --------------------------------------------------------------------- //
// JQUERY FN
// --------------------------------------------------------------------- //
$.fn.jSlots = function(options){
if (this.length) {
return this.each(function(){
(new $.jSlots(this, options));
});
}
};
})(jQuery);
The core functionality is the same as in the github repository.
The important part, I think, is the function spinEm:
spinEm : function() {
var that = this;
that.$el
.css( 'top', -base.listHeight )
.animate( { 'top' : '0px' }, that.spinSpeed, 'linear', function() {
that.lowerSpeed();
});
}
here the list is placed above the jSlotsWrapper and with the animate function it moves down. Now what I need is for the animation to continue, and not to place the list at the top again. How can I achieve that.
EDIT
Ok, i tried the following to avoid the empty space, everytime the animation has finished:
spinEm : function() {
var that = this;
that.$el
.css( 'bottom', $("body").height() )
.animate( { 'top' : '0px' }, that.spinSpeed, 'linear', function() {
that.lowerSpeed();
});
}
I try to place the list at the bottom of the box and move it down until the top appears. But somehow the list doesn't really move. It just moves for 1 word and then stops comletely. What is wrong in the animation code?
EDIT
Ok I found the solution to my problem. Apparently, I can't use bottom in the css function. Instead, I used top and calculated the position of the top border of the list. That way I have an animation without all the empty space at the beginning. To avoid the jumping from the bottom to the top of the list I modified the height of the jSlots-Wrapper and the order of the list items, so that the items that are displayed before and after the jump are the same. That way, the user doesn't see the list jumping.
here is my new animate function.
spinEm : function() {
var that = this;
that.$el
.css( 'top', -(base.listHeight - $("body").height()) )
.animate( { 'top' : '0px'}, that.spinSpeed, 'linear', function() {
that.lowerSpeed();
});
}
I found a way to make the animation so that the user doesn't see the jumping. What I did, is, I configured the list in a way so that the beginning and the end are the same. So that when the end of the list is reached and it jumps to the beginning again, there is no difference. The jump is still there, but not visible for the user.
I have this code:
jQuery/JavaScript
$(document).ready(function () {
function min() {
var number = parseInt($('span').html());
return number - 30;
}
function add() {
var number = parseInt($('span').html());
return number + 31;
}
$("#container").click(function () {
$('span').text(min());
});
$("#box").click(function () {
$('span').text(add());
});
var time = parseInt($('b').html());
if (time <= 0) {
alert("AAAAA");
};
});
CSS
#container{
background: #00ff00;
width: 500px;
height:500px;
}
#box{
background: black;
width: 100px;
height:100px;
color: white;
cursor: pointer;
}
HTML
<div id="container">
<span> 60 </span>
<div id="box"> </div>
</div>
when you click on you text in change for +31 and -30 so you will got 61 because default is 60 and but if you click on text in span will change for -30 only and it will display 30 i wish to alert when text in span reach 0 i made this but didn't work.
does any one know how to fix it?
I think that I'm not understanding completely to you. Maybe this the next link can help you.
You have some errors, check the solution.
$(document).ready(function(){
var $span = $('span');
function min() {
var number = parseInt($span.html());
return number - 30;
}
function add() {
var number = parseInt($span.html());
return number + 31;
}
$("#container").click(function(){
$('span').text(min());
checkTime();
});
$("#box").click(function(){
$('span').text(add());
checkTime();
});
function checkTime() {
debugger
var time = parseInt($span.html());
if (time <= 0) {
alert("AAAAA");
};
}
});
Please next time publish your problem in JSfiddle or similar.
I think you're selector to get the span is incorrect. You also need to execute the check after you decrement the value.
$(document).ready(function(){
function min() {
var number = parseInt($('span').html());
return number - 30;
}
function add() {
var number = parseInt($('span').html());
return number + 31;
}
$("#container").click(function(){
$('span').text(min());
CheckValue();
});
$("#box").click(function(){
$('span').text(add());
});
function CheckValue() {
var val = parseInt($('#container > span').html());
if (val <= 0) {
alert("AAAAA");
}
}
);