Как сделать так чтобы шарик при перемещении его мышкой не выходил за пределы границ поля

Приравнял вверх объекта к верхней линии рамки, но шар двигается только вправо-влево, подскажите пожалуйста как сделать так, чтобы он двигался вверх и вниз и притом упирался в границы рамки. Приравнял я вот в этом цикле.

if (ball.offsetTop <= containerTop) { ball.style.top = containerTop + 'px'};

// Array of available ball colors
var colors = ['red', 'blue', 'green', 'yellow'];

// Create a grid of random color balls
var grid = createGrid(6, 6);

// Render the grid on the web page
renderGrid();

// Function to create a grid of random color balls
function createGrid(rows, columns) {
  var grid = [];
  for (var i = 0; i < rows; i++) {
    var row = [];
    for (var j = 0; j < columns; j++) {
      // Generate a random color for each ball
      var randomColor = colors[Math.floor(Math.random() * colors.length)];
      row.push(randomColor);
    }
    grid.push(row);
  }
  return grid;
}

// Function to render the grid on the web page
function renderGrid() {
  var gridContainer = document.getElementById('gridContainer');
  gridContainer.innerHTML = '';

  for (var i = 0; i < grid.length; i++) {
    for (var j = 0; j < grid[i].length; j++) {
      var ball = document.createElement('div');
      ball.id = `ball-${i}-${j}`;
      ball.className = 'ball ' + grid[i][j];
      ball.addEventListener('mousedown', createMouseDownListener(ball));
      ball.addEventListener('mousmove', createMouseDownListener(ball));
      ball.addEventListener('mouseup', createMouseDownListener(ball));
      gridContainer.appendChild(ball);
    }
    gridContainer.appendChild(document.createElement('br'));
  }
}

// Function to create the mousedown event listener for a ball element

function createMouseDownListener(ball) {

  return function(event) {
    var gridContainer = document.getElementById('gridContainer');
    var containerTop = gridContainer.offsetTop; // Позиция верхней линии
    var containerBottom = containerTop + gridContainer.offsetHeight;
    var initialX = event.clientX;
    var initialY = event.clientY;
    var initialLeft = parseInt(ball.style.left) || 0;
    var initialTop = parseInt(ball.style.top) || 0;

    var listener = function(e) {
      var deltaX = e.clientX - initialX;
      var deltaY = e.clientY - initialY;
      if (ball.offsetTop <= containerTop) {
        ball.style.top = containerTop + 'px';

      }
      ball.style.left = initialLeft + deltaX + 'px';
      //ball.style.top = initialTop + deltaY + 'px';
    };



    document.addEventListener('mousemove', listener);
    document.addEventListener('mouseup', function() {
      document.removeEventListener('mousemove', listener);

    });
  }
}
.ball {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin: 5px;
  display: inline-block;
  cursor: pointer;
  position: relative;
}

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

.green {
  background-color: green;
}

.yellow {
  background-color: yellow;
}

#gridContainer {
  border: 2px solid black;
  padding: 10px;
  display: inline-block;
  position: relative;
  /* Add position relative */
  overflow: hidden;
  /* Add overflow hidden */
}
<h1>Color Matching Game</h1>
<div id="gridContainer"></div>


Ответы (0 шт):