Bouncing Ball - Rough Hack

Starting point of a class exercise where we make incremental improvements.

HTML

<h1>Bouncing Ball</h1>

<div id="canvas">
</div>

CSS

h1 {
    text-align: center;
}

#canvas {
    background-color: #ccddcc;
    margin: 1em auto;
}

.ball {
    background-color: black;
    position: relative;
    border-radius: 50%;
}

JavaScript

var canvas = {
    element: document.getElementById('canvas'),
    width: 600,
    height: 400,
    initialize: function () {
        this.element.style.width = this.width + 'px';
        this.element.style.height = this.height + 'px';
        document.body.appendChild(this.element);
    }
};

var ball = {
    element: document.createElement('div'),
    width: 40,
    height: 40,
    dx: 4,
    dy: 3,
    initialize: function () {
        this.element.className += ' ball';
        this.element.style.width = this.width + 'px';
        this.element.style.height = this.height + 'px';
        canvas.element.appendChild(this.element);
    },
    moveTo: function (x, y) {
        this.element.style.left = x + 'px';
        this.element.style.top = y + 'px';
    },
    changeDirectionIfNecessary: function (x, y) {
        if (x < 0 || x > canvas.width - ball.width) {
            this.dx = -this.dx;
        }
        if (y < 0 || y > canvas.height - ball.height) {
            this.dy = -this.dy;
        }
    },
    draw: function (x, y) {
        this.moveTo(x, y);
        var ball = this;
        setTimeout(function () {
            ball.changeDirectionIfNecessary(x, y);
            ball.draw(x + ball.dx, y + ball.dy);
        }, 1000 / 15);
    }
};



canvas.initialize();
ball.initialize();
ball.draw(0, 0);


function isIntersect(point, ball) {
  return (Math.pow(Math.sqrt(point.x-ball.offsetLeft)) + Math.pow(Math.sqrt(point.y-ball.offsetTop))) < 40;
}

/* canvas.addEventListener('click', (e) => {
  const pos = {
    x: e.clientX,
    y: e.clientY
  };
  circles.forEach(circle => {
    if (isIntersect(mousePoint, circle)) {
      alert('click on circle: ' + circle.id);
    }
  });
}); */


canvas.element.addEventListener('click', function(event) {
    const pos = {
      x: event.clientX,
      y: event.clientY
    };
    
    if (isIntersect(pos, ball.element)) {
      alert('click on circle');
    }
    
    
    /* var x = event.pageX - canvas.element.offsetLeft,
...