Skip to content
Advertisement

Start and stop with keypress from keyboard

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:

 var output, started, duration, desired;

// Constants
duration = 5000;
desired = '5';

// Initial setup
output = $('#output');
started = new Date().getTime();

// Animate!
animationTimer = setInterval(function() {
    // If the value is what we want, stop animating
    // or if the duration has been exceeded, stop animating
    if (output.text().trim() === desired || new Date().getTime() - started > duration) {
        clearInterval(animationTimer);
    } else {
        console.log('animating');
        // Generate a random string to use for the next animation step
        output.text(
            ''+
            Math.floor(Math.random() * 10)+
            Math.floor(Math.random() * 10)
        );
    }
}, 100);

Advertisement

Answer

You can wrap the animation in a function and then call it on keypress… something like this:

var output, started, duration, desired;
var sel = [];
// Constants
duration = 5000;
desired = '5';

// Initial setup
output = $('#output');

var keyPressed = false;

$(document).keypress(function(){
	if (!keyPressed){
  	started = new Date().getTime();
  	scramble();
    keyPressed = true;
  }
  else{
  	keyPressed = false;
  }
});

// Animate!
var scramble = function(){
	animationTimer = setInterval(function() {
    // If the value is what we want, stop animating
    // or if the duration has been exceeded, stop animating
    if (output.text().trim() === desired || new Date().getTime() - started > duration || !keyPressed) {
    		while($.inArray(output.text().trim(),sel)>-1){
        	output.text(
              ''+
              Math.floor(Math.random() * 10)+
              Math.floor(Math.random() * 10)
          );
        }
        clearInterval(animationTimer);
        keyPressed = false;
        sel.push(output.text());
        $("#selected").text(sel);
    } else {
        
        // Generate a random string to use for the next animation step
        output.text(
            ''+
            Math.floor(Math.random() * 10)+
            Math.floor(Math.random() * 10)
        );
        
    }
	}, 100);
}
#output {
    margin: 20px;
    padding: 20px;
    background: gray;
    border-radius: 10px;
    font-size: 80px;
    width: 80px;
    color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">--</div>
<div id="selected"></div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement