I have this JavaScript http://jsfiddle.net/ZDsMa/433/ to pick a random number. I put this on html div and I want to start scrambling the numbers with keypress
instead of onClick
, also to stop again with keypress
:
JavaScript
x
27
27
1
var output, started, duration, desired;
2
3
// Constants
4
duration = 5000;
5
desired = '5';
6
7
// Initial setup
8
output = $('#output');
9
started = new Date().getTime();
10
11
// Animate!
12
animationTimer = setInterval(function() {
13
// If the value is what we want, stop animating
14
// or if the duration has been exceeded, stop animating
15
if (output.text().trim() === desired || new Date().getTime() - started > duration) {
16
clearInterval(animationTimer);
17
} else {
18
console.log('animating');
19
// Generate a random string to use for the next animation step
20
output.text(
21
''+
22
Math.floor(Math.random() * 10)+
23
Math.floor(Math.random() * 10)
24
);
25
}
26
}, 100);
27
Advertisement
Answer
You can wrap the animation in a function and then call it on keypress… something like this:
JavaScript
1
51
51
1
var output, started, duration, desired;
2
var sel = [];
3
// Constants
4
duration = 5000;
5
desired = '5';
6
7
// Initial setup
8
output = $('#output');
9
10
var keyPressed = false;
11
12
$(document).keypress(function(){
13
if (!keyPressed){
14
started = new Date().getTime();
15
scramble();
16
keyPressed = true;
17
}
18
else{
19
keyPressed = false;
20
}
21
});
22
23
// Animate!
24
var scramble = function(){
25
animationTimer = setInterval(function() {
26
// If the value is what we want, stop animating
27
// or if the duration has been exceeded, stop animating
28
if (output.text().trim() === desired || new Date().getTime() - started > duration || !keyPressed) {
29
while($.inArray(output.text().trim(),sel)>-1){
30
output.text(
31
''+
32
Math.floor(Math.random() * 10)+
33
Math.floor(Math.random() * 10)
34
);
35
}
36
clearInterval(animationTimer);
37
keyPressed = false;
38
sel.push(output.text());
39
$("#selected").text(sel);
40
} else {
41
42
// Generate a random string to use for the next animation step
43
output.text(
44
''+
45
Math.floor(Math.random() * 10)+
46
Math.floor(Math.random() * 10)
47
);
48
49
}
50
}, 100);
51
}
JavaScript
1
9
1
#output {
2
margin: 20px;
3
padding: 20px;
4
background: gray;
5
border-radius: 10px;
6
font-size: 80px;
7
width: 80px;
8
color: white;
9
}
JavaScript
1
3
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
2
<div id="output">--</div>
3
<div id="selected"></div>