How can I make the rectangles move in columns when I pick them up?

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Sobics Game</title>
	<style>
		#screen{
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			display: flex;
			justify-content: center;
		}
		#game-board {
			margin-top: 10px;
			width: 100%;
			height: 90%;
			margin: 50px 20px 0px 20px;
			border: 2px solid #999;
			border-radius: 3px;
		}
		.row {
			display: flex;
		}
		.rectangle {
			width: 10%;
			height: 40px;
			margin: 3px;
			cursor: pointer;
			user-select: none;
			border-radius: 3px;
		}
		.visible{
			box-shadow: 1px 1px 1px 1px #000;
		}
		.selected {
			border: 2px solid white;
		}
		#startBtn{
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%,-50%);
		}
		#startBtn, #restartBtn{
			background-color: #1c9e6c;
			border: none;
			border-radius: 10px;
			font-size: 2.5rem;
			color: #fff;
			padding: 10px;
			box-shadow: 5px 5px 10px 0px #257053;
		}
		#startBtn:hover, #restartBtn:hover{
			background-color: #19bf7f;
		}
		#startBtn:active, #restartBtn:active{
			box-shadow: none;
			vertical-align: top;
			padding: 8px 10px 6px;
		}
		#overlay{
			position: fixed;
			top: 0;
			left: 0;
			display: flex;
			justify-content: center;
			align-items: center;
		}
		#menu{
			display: none;
			background-color: #000;
			opacity: 0.8;
			padding: 25px 75px 25px 75px;
			justify-content: center;
			flex-flow: column;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%,-50%);
		}
		#leaderboard-container{
			height: 300px;
			overflow-y: scroll;
			margin-top: 30px;
		}
		#leaderboard-container h2{
			color: #fff;
			font-size: 28px;
		}
		#leaderboard-container li{
			color: #ccc;
			font-size: 22px;
		}
		#score{
			position: absolute;
			top: 5px;
			font-size: 24px;
			background-color: #e3e3e3;
			padding: 5px 10px 5px 10px;
			border-radius: 5px;
		}
		#mute{
			position: fixed;
			left: 10px;
			top: 10px;
			background-color: #fff;
			border: 1px solid #000;
			border-radius: 5px;
			font-size: 16px;
		}
	</style>
</head>
<body>
	<div id="screen">
		<div id="score"></div>
		<button id="mute" onclick="mute()">Mute</button>
		<div id="game-board"></div>
	</div>
	<button id="startBtn" onclick="startGame()">Start Game</button>
	<div id="menu">
		<button id="restartBtn" onclick="restartGame()">Restart</button>
		<div id="leaderboard-container"></div>
	</div>
	

	<script>
		const boardWidth = 10;
		const boardHeight = 14;
		const numFilledRows = 5;
    const backgroundMusic = new Audio('../music/backgroundmusic.mp3');
    let isGameEnded = false;
	
	muteCount = 0;
	function mute(){
		const btn = document.getElementById('mute');
		if(muteCount%2 == 0){
			btn.textContent = "Unmute";
			backgroundMusic.muted = true;
		}else{
			btn.textContent = "Mute";
			backgroundMusic.muted = false;
		}
		muteCount++;
	}
	
		function restartGame() {
  // Stop the background music
  backgroundMusic.pause();
  backgroundMusic.currentTime = 0;

  // Clear the game board and reset the score
  document.getElementById("menu").style.display = "none";
  const gameBoard = document.getElementById('game-board');
  gameBoard.innerHTML = '';
  const scoreElement = document.getElementById('score');
  scoreElement.innerHTML = 'Score: 0';

  // Reset the game variables
  click = 0;
  draggedRectangles = [];
  numberOfRectangles = 0;
  rectangleColor = null;
  i = 0;
  pickedUpRectangles = 0;
  isGameEnded = false;

  // Start a new game
  startGame();
}

		function startGame() {
			document.getElementById("startBtn").style.display = "none";
			const gameBoard = document.getElementById('game-board');
			gameBoard.innerHTML = '';

			for (let row = 0; row < boardHeight; row++) {
				const divRow = document.createElement('div');
				divRow.classList.add('row');

				for (let col = 0; col < boardWidth; col++) {
					const divRectangle = document.createElement('div');
					divRectangle.classList.add('rectangle');
					divRectangle.addEventListener("click", pickRectangle);
					if (row < numFilledRows) {
						divRectangle.style.backgroundColor = getRandomColor();
						divRectangle.classList.add('visible');
					}
					divRow.appendChild(divRectangle);
				}

				gameBoard.appendChild(divRow);
			}
          // Create a new HTML element to display the score
      const scoreElement = document.getElementById("score");
      scoreElement.innerHTML = 'Score: 0'; // Initialize score value in the element

      backgroundMusic.play();
      backgroundMusic.loop = true;

      setTimerAndAddRow();
		}

		function getRandomColor() {
			const colors = ['red', 'blue', 'green', 'yellow', 'purple', 'orange'];
			const randomIndex = Math.floor(Math.random() * colors.length);
			return colors[randomIndex];
		}


let click = 0;    
let draggedRectangles = [];
let numberOfRectangles = 0;
let rectangleColor = null;
let i = 0;
let pickedUpRectangles = 0;

function pickRectangle(event) {
    if (click === 0) {
        const gameBoard = document.getElementById("game-board");
        const boardRect = gameBoard.getBoundingClientRect();
        const columnWidth = gameBoard.offsetWidth / boardWidth;
        const columnIndex = Math.floor((event.clientX - boardRect.left) / columnWidth);
        draggedRectangles.push(...getColoredRectangles(columnIndex));

        // Find the bottom-most empty row in that column
        const rectangles = document.getElementsByClassName("rectangle");
        rectangleColor = draggedRectangles[0].style.backgroundColor;
        numberOfRectangles = draggedRectangles.length;
        pickedUpRectangles = draggedRectangles.length;
        draggedRectangles.forEach(rectangle => {
            rectangle.style.backgroundColor = "";
			rectangle.classList.remove("visible");
        });

        for (let row = boardHeight - 1; row >= 0; row--) {
            const index = row * boardWidth + columnIndex;
            const rectangle = rectangles[index];

            if (!rectangle.style.backgroundColor) {
                rectangle.style.backgroundColor = rectangleColor;
				rectangle.classList.add("visible");
                draggedRectangles[i] = rectangle;
                numberOfRectangles--;
                i++;
                if (numberOfRectangles === 0) {
                    break;
                }
            }
        }

        document.addEventListener("mousemove", dragRectangle);
        click = 1;
        i = 0;
    } else if (click === 1) {

        // Find the column that the mouse is in
        const gameBoard = document.getElementById("game-board");
        const boardRect = gameBoard.getBoundingClientRect();
        const columnWidth = gameBoard.offsetWidth / boardWidth;
        const columnIndex = Math.floor((event.clientX - boardRect.left) / columnWidth);

        // Find the bottom-most empty row in that column
        const rectangles = document.getElementsByClassName("rectangle");

        // Restore colors for the dragged rectangles and place them
        draggedRectangles.forEach(rectangle => {
            const rectanglePlace = getLastNonColoredRectangle(columnIndex);
            if (rectanglePlace) {
                rectangle.style.backgroundColor = "";
				rectangle.classList.remove("visible");
                rectanglePlace.style.backgroundColor = rectangleColor;
				rectanglePlace.classList.add("visible");
            }
        });

        let rectanglePlace = getLastNonColoredRectangle(columnIndex);
        const rectangleIndex = Array.from(rectangles).indexOf(rectanglePlace) - 10;
        console.log(rectangleIndex);

        click = 0;
        document.removeEventListener("mousemove", dragRectangle);
        checkConnectedRectangles(rectangleColor, rectangleIndex);
        draggedRectangles = [];
    }
}

function dragRectangle(event) {
  if (draggedRectangles.length > 0) {
    draggedRectangles.forEach((draggedRectangle) => {
      draggedRectangle.style.left = event.clientX - draggedRectangle.offsetWidth / 2 + 'px';
      draggedRectangle.style.top = event.clientY - draggedRectangle.offsetHeight / 2 + 'px';
    });
  }
}

function getLastNonColoredRectangle(columnIndex) {
  const rectangles = document.getElementsByClassName('rectangle');
  let lastNonColoredRectangle = null;
  
  for (let row = 0; row < boardHeight - 4; row++) {
    const index = row * boardWidth + columnIndex;
    const rectangle = rectangles[index];
    
    if (!rectangle.style.backgroundColor) {
      lastNonColoredRectangle = rectangle;
      break;
    }
  }
  
  return lastNonColoredRectangle;
}

function getColoredRectangles(columnIndex) {
    const rectangles = document.getElementsByClassName("rectangle");
    const coloredRectangles = [];
    let rectangleColor = null;

    for (let row = boardHeight - 4; row >= 0; row--) {
        const index = row * boardWidth + columnIndex;
        const rectangle = rectangles[index];

        if (rectangle.style.backgroundColor) {
            if (rectangleColor === null) {
                rectangleColor = rectangle.style.backgroundColor;
            }
            if (rectangleColor && rectangle.style.backgroundColor === rectangleColor) {
                coloredRectangles.push(rectangle);
            } else if (rectangleColor !== null && rectangle.style.backgroundColor !== rectangleColor) {
                break;
            }
        }
    }

    return coloredRectangles;
}

let score = 0;

function checkConnectedRectangles(rectangleColor, index) {
  const rectangles = document.getElementsByClassName("rectangle");
  const draggedRow = Math.floor(index / boardWidth);
  const draggedCol = index % boardWidth;

  const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];
  let totalCount = 0;
  let indicesToClear = new Set();

  function checkForConnected(row, col) {
    const index = row * boardWidth + col;
    console.log("Lefutok gecisbugyi " + index);
    if (
      row >= 0 &&
      row < boardHeight &&
      col >= 0 &&
      col < boardWidth &&
      rectangles[index].style.backgroundColor === rectangleColor
    ) {
      console.log(indicesToClear);
      const alreadyChecked = indicesToClear.has(index);
      console.log(alreadyChecked);
      if (!alreadyChecked) {
        indicesToClear.add(index);
        // Check for connected rectangles in all directions
        directions.forEach(([rowStep, colStep]) => {
          const currentRow = row + rowStep;
          const currentCol = col + colStep;
          console.log(currentRow + " row geci");
          console.log(currentCol + " col geci");
          checkForConnected(currentRow, currentCol);
        });
      }
    }
  }

  // Check the starting rectangle
  checkForConnected(draggedRow, draggedCol);
  totalCount = indicesToClear.size;

  if (totalCount >= 4) {
    // Found 4 connected rectangles, make them transparent
    indicesToClear.forEach((indexToClear) => {
      rectangles[indexToClear].style.backgroundColor = "";
	  rectangles[indexToClear].classList.remove("visible");
    });
    score += 100 * totalCount;
    document.getElementById("score").innerHTML = "Score: " + score;
    checkGapsInColumns();
  }
}

function checkGapsInColumns() {
  const rectangles = document.getElementsByClassName("rectangle");
  
  for (let col = 0; col < boardWidth; col++) {
    let coloredRectCount = 0;
    
    // Count how many colored rectangles are present in the current column
    for (let row = 0; row < boardHeight - 4; row++) {
      const index = row * boardWidth + col;
      const rectangle = rectangles[index];
      
      if (rectangle.style.backgroundColor) {
        coloredRectCount++;
      }
    }

    // Check for gaps between colored rectangles
    let gapRow = -1;
    for (let row = 0; row < boardHeight - 5 && coloredRectCount > 0; row++) {
      const index = row * boardWidth + col;
      const rectangle = rectangles[index];
      
      if (gapRow === -1 && !rectangle.style.backgroundColor) {
        gapRow = row;
      } else if (rectangle.style.backgroundColor) {
        if (gapRow !== -1) {
          const gapIndex = gapRow * boardWidth + col;
          const emptyRectangle = rectangles[gapIndex];

          emptyRectangle.style.backgroundColor = rectangle.style.backgroundColor;
		  emptyRectangle.classList.add("visible");
          rectangle.style.backgroundColor = "";
		  rectangle.classList.remove("visible");
          console.log("checkGapsdarab " + gapIndex);
          console.log(emptyRectangle.style.backgroundColor);
          checkConnectedRectangles(emptyRectangle.style.backgroundColor, gapIndex);
          gapRow++;
        }
        coloredRectCount--;
      }
    }
  }
}

function addRowToTop() {
  const gameBoard = document.getElementById('game-board');
  const rowDivs = gameBoard.querySelectorAll('.row');

  // Get the colors of the rectangles in the bottom row
  const bottomRowRectangles = rowDivs[rowDivs.length - 1].querySelectorAll('.rectangle');
  const bottomRowColors = Array.from(bottomRowRectangles).map(rectangle => rectangle.style.backgroundColor);

  // Shift all rows down by 1
  for (let i = rowDivs.length - 5; i > 0; i--) {
    const currentRowRectangles = rowDivs[i].querySelectorAll('.rectangle');
    const prevRowRectangles = rowDivs[i - 1].querySelectorAll('.rectangle');

    Array.from(currentRowRectangles).forEach((rectangle, index) => {
      const prevRectangle = prevRowRectangles[index];
      rectangle.style.backgroundColor = prevRectangle.style.backgroundColor;
      rectangle.classList.toggle('visible', prevRectangle.classList.contains('visible'));
    });
  }

  // Fill the first row with new colors
  const firstRowRectangles = rowDivs[0].querySelectorAll('.rectangle');
  Array.from(firstRowRectangles).forEach((rectangle, index) => {
    rectangle.style.backgroundColor = bottomRowColors[index] || getRandomColor();
    rectangle.classList.add("visible");
  });

  checkColumns();
  setTimerAndAddRow();
}

let cycle = 1;

function setTimerAndAddRow() {
    if(!isGameEnded){
    setTimeout(addRowToTop, 20/cycle * 1000);
    cycle += 0.05;
    }
}

function checkColumns() {
  const rectangles = document.getElementsByClassName("rectangle");
  for (let col = 0; col < boardWidth; col++) {
    let count = 0;
    for (let row = boardHeight - 4; row >= 0; row--) {
      const index = row * boardWidth + col;
      const rectangle = rectangles[index];
      if (rectangle.classList.contains("visible")) {
        count++;
      }
    }
    if (count >= 10) {
      endGame();
      return;
    }
  }
}

function endGame() {
  isGameEnded = true;
  document.getElementById("menu").style.display = "flex";
  document.removeEventListener("mousemove", dragRectangle);
  backgroundMusic.pause();
  const playerName = prompt("Game over! Enter your name:");
  if (playerName) {
    updateLeaderboard(playerName, score);
    displayLeaderboard();
  }
}

	</script>
</body>
</html>