Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating DIV spins slowly on second click

I think I overlooked something. This is a very simple spin-the-bottle game.

Javascript/jQuery

$('.bottle').on('click', function(e) {
    this.removeAttribute('style');
    var deg = 3000 + Math.round(Math.random() * 500);
    var css = '-webkit-transform: rotate(' + deg + 'deg);';

    this.setAttribute(
        'style', css
    );
});

CSS:

.bottle {
    width: 200px;
    height: 200px;
    background-image: url(img/bottle.png);
    -webkit-transition: -webkit-transform 6s ease-out;
}

HTML:

<div class="bottle"></div>

This works perfectly on the first click of the bottle. But starting from the second click, the spin is very very slow?

like image 977
Martin Lyder Avatar asked Dec 27 '22 12:12

Martin Lyder


2 Answers

Try this : http://jsfiddle.net/sMcAN/

var i = 1;
$('.bottle').on('click', function(e) {
this.removeAttribute('style');
var deg = 3000 + Math.round(Math.random() * 500);
deg = ((-1) ^ i) * deg;

var css = '-webkit-transform: rotate(' + deg + 'deg);';
this.setAttribute('style', css);
i++;
});​

Another update : http://jsfiddle.net/sMcAN/2/

like image 124
Anujith Avatar answered Dec 29 '22 00:12

Anujith


This is because at first, you are going from 0 to a value over 3000. But then, the value is always within 3000 - so the difference is not big enough and it still takes the 6 seconds you have defined.

One solution would be to make sure that you offset the value and make it different by few thousand each time.

var i = 0, offset = [2000, 4000, 6000, 3000, 5000, 1000];

$('.bottle').on('click', function(e) {
  this.removeAttribute('style');

  var deg = offset[i] + Math.round(Math.random() * 500);
  i++;
  if (i > 5) {
    i = 0;
  }

  var css = '-webkit-transform: rotate(' + deg + 'deg);';

  this.setAttribute(
    'style', css
 );
});​
like image 24
dakdad Avatar answered Dec 29 '22 02:12

dakdad