4

I created a roulette animation by manipulating the "margin-left" option with jquery. I want it to move back to the start position after every roll, so i tried to reset "margin-left" 5 seconds after every roll.

$(document).ready(function() {
  $("#roll").click(function() {
    $("#roulette").css("margin-left","-3000px").delay(5000);
    $("#roulette").queue(function() {
        $('#roulette').css("margin-left","0px");
      }).dequeue();
  });
});

HTML:

<div class="row roulette-outer">
    <div class="row roulette" id="roulette">
      <div class="skins"><img class="img-thumbnail" src="images/1.png"></img></div>
      <div class="skins"><img class="img-thumbnail" src="images/2.png"></img></div>
      ...
    </div>
</div>
<button class="btn btn-danger center-block" type="button" id="roll">Klick</button>

It's working but i have to double click the "roll"-Button or it won't move.

1 Answers1

2

The .dequeue() method is making the queued function execute immediately, moving the #roulette element back to its original place. The code, as it is, will only work when there is already something in the queue.

What you’re doing doesn’t require complicated queuing, so the code can be simplified a bit, probably best by using vanilla JavaScript to handle the delayed code, see the discussion here.

This will give the behavior you are looking for:

  $(document).ready(function() {
  $("#roll").click(function() {
    $("#roulette").css("margin-left","-3000px");
    window.setTimeout( function() { $("#roulette").css("margin-left","0") }, 5000 );
  });
});
Community
  • 1
  • 1
Tim Grant
  • 3,300
  • 4
  • 23
  • 31