Click button


HTML to create button and square

<!-- Button -->
<button onclick="toggleColor()" style="padding: 10px 20px; font-size: 16px;">
  Toggle Color
</button>

<!-- Square -->
<div id="colorBox" style="width: 200px; height: 200px; background-color: lightgrey; margin-top: 20px;"></div>

javascript to change square to a random color when button clicked

<!-- JavaScript -->
<script>
  function toggleColor() {
    const box = document.getElementById('colorBox');

    // Update to random color
    const randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);
    box.style.backgroundColor = randomColor;
  }
</script>