0

I'm trying to achieve a mouseover effect. When the usere hovers the element, it start spinning slowly and over time the speed will increase. When the user leaves the element, the spinning will decrease and eventually stop.

My approach would be to set a loop, that multiplies the given value 1. That works.

Now when the user leaves, I somehow have to get the value and divide it by some number. Thats not working :-(

Here my code, I use jQuery

https://codepen.io/hhqh/pen/gOOVQPV?editors=1011

var deg = 1;
var img;

var keepGoing = true;
var keepStopping = true;

function myLoop(img) {
  console.log(img);
  deg *= 1.1;
  console.log(deg);
  img.css('transform', 'rotate(' + deg + 'deg)');

  if(keepGoing) {
    setTimeout(myLoop, 30, img);
  }
}

function myStop(img) {

  console.log(img);
  deg /= 1.1;
  console.log(deg);
  img.css('transform', 'rotate(' + deg + 'deg)');

  if(keepStopping) {
    setTimeout(myStop, 30, img);
  }
}



$('#spinner').on('mouseenter', function(){
  var img = $(this).find('img');
  startLoop(img);
}).on('mouseleave', function(){
  var img = $(this).find('img');
  stopLoop(img);
});

function startLoop(img) {
  keepGoing = true;
  keepStopping = false;
  myLoop(img);
}

function stopLoop(img) {
  keepGoing = false;
  keepStopping = true;
  myStop(img);
}

As you see, it just jumps back. I want to slowly decrease the value, but because it rotates and just adds up the number, decreasing actually rotates it backwards. Maybe I have to get the current rotation, and make a new calculus that is some how adding a decreasing number. No idea how..

1 Answers1

0

You have to stop myStop function in a specific condition, when rotation degrees is at starting position.

function myStop(img) {

  console.log(img);
  deg /= 1.1;
  console.log(deg);
  if (deg.toFixed(1) < 0.1) {
    return;
  }
  img.css('transform', 'rotate(' + deg + 'deg)');

  if(keepStopping) {
    setTimeout(myStop, 30, img);
  }
}
t3x4r
  • 19
  • 3