Click handler is called several times in jQuery animation

I am familiar with jQuery and am creating a small application in which the red screen moves around the screen, and the user should try to click on it, and when the user makes a window alert(), but the problem is that it alert()continues to appear even after clicking "ok". The only way to stop this is to click OK repeatedly, and in the end he quits.

Here is the code that displays the warning window:

function Animate() {
    var _newPosition = GetNewPosition();
    // Sets new position of div
    div.animate({
        top: _newPosition[0],
        left: _newPosition[1]
    }, function () {
        div.on('click', function () {
            alert('You clicked the box!');
        });
        Animate();
    });
}

Here is my JSFiddle that reproduces the problem

I initially thought I could solve this by returning falseafter the call alert(), for example:

div.on('click', function () {
    alert('You clicked the box!');
    return false;
});

But that didn't work either.

, , , , , .

+4
2

, click . , .

, .

function Animate() {
    var _newPosition = GetNewPosition();
    // Sets new position of div
    div.animate({
        top: _newPosition[0],
        left: _newPosition[1]
    }, Animate);
}

ready()

$(document).ready(function () {
    Animate();

    div.on('click', function() {
        // Code here
        alert('clicked');
    });
});

Animate

function() {
    Animate();
}

Animate, , .


:

  • mousedown
  • Animate.

FIddle

var div = $('#box');
$(document).ready(function() {
  Animate();

  div.on('mousedown', function() {
    // Code here
    console.log('clicked');
  });
});

function GetNewPosition() {
  // Get dimentions of the window and remove the div area
  var h = $(window).height() - 50;
  var w = $(window).width() - 50;
  // New height and width is auto generated
  var nh = Math.floor(Math.random() * h);
  var nw = Math.floor(Math.random() * w);
  return [nh, nw];
}

function Animate() {
  var _newPosition = GetNewPosition();
  // Sets new position of div
  div.animate({
    top: _newPosition[0],
    left: _newPosition[1]
  }, (Math.floor(Math.random() * 5000) + 1), Animate);
}
#box {
  width: 50px;
  height: 50px;
  background-color: red;
  position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 id="success"></h3>
<div id="box"></div>
Hide result
+6

, . click animate $(document).ready(function () {});, .

jsfiddle

+1

Source: https://habr.com/ru/post/1617165/


All Articles