How do I "update" a function?

0

Well, I have the following code:

<head>
<style>
body,html,div {
  margin:0;
  padding:0;
  width:1050px;
  height:69px;
  position:relative;
}

#anim {
  background:url('https://csgopolygon.com/img/cases.png?v=222') 0 0;
  background-size:300% 100%;
}
#ponteiro{
background-color:yellow;
height:69px;
width:5px;

}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
</head>



<div id="anim">
<center>
<div id="ponteiro">
</div>
</center>


</div>

<button onclick="goncalo()">Rodar!</button>

<script type="text/javascript"> 
function goncalo(){

var ola = Math.floor(Math.random() * 500) + 150  +'%';
$('#anim').animate({'background-position-x': ola},8000,'easeOutCubic');

}
</script>

When I enter the page and click on Run !, it works the way I want it, but then if I do not give f5 on the same page and click on it, it does not have the same effect or instead of "turning from left to the right "wheel runs from right to left. How can I do so that at the end of the "Rotate" effect, update the function so that you do not have to give f5?

Thank you.

    
asked by anonymous 29.01.2017 / 17:01

1 answer

3

What is happening is that in the second round he can pick up a random number for the lower bottom position than the previous one, and then the animation goes to the right.

One suggestion is to restart the background position before animating it. You can use jQuery's .css method to set this attribute to 0% .

Something like this:

function goncalo() {

  var ola = Math.floor(Math.random() * 500) + 150 + '%';
  $('#anim').css('background-position-x', "0%");
  $('#anim').animate({
    'background-position-x': ola
  }, 8000, 'easeOutCubic');

}

Fiddle with my suggestion: link

Editing: add-in

If you click rotate while the animation is in progress, the same problem will occur. So I took the liberty of adding a control to your code: if data-animating is set to "true", it returns from the function and does not execute another animation. At the end of the animation, it removes this attribute (I added the callback to the end of the .animate method). It's just a suggestion:

function goncalo() {

  var obj = $('#anim');

  var isAnimating = obj.attr('data-animating');
  if (isAnimating === "true") return;

  var ola = Math.floor(Math.random() * 500) + 150 + '%';    

  obj.css('background-position-x', "0%");
  obj.attr('data-animating', 'true')
  obj.animate({
    'background-position-x': ola
  }, 8000, 'easeOutCubic', function() {
    obj.removeAttr('data-animating')
  });

}

Fiddle here with this update: link

Another approach would be to simply disable the button while the animation is in progress.

    
29.01.2017 / 17:10