Vanilla JS: Thay đổi ngẫu nhiên màu nền

https://viblo.asia/p/vanilla-js-thay-doi-ngau-nhien-mau-nen-YWOZroNYlQ0

by trung ken

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css">
<button class="btn btn-primary">Thay đổi ngẫu nhiên màu nền</button>

CSS

body {width: 100vw;height: 100vh;display: flex;align-items: center;justify-content: center;}

JavaScript

let currentColor = 'transparent'
const listColors = ['red', 'orange', 'yellow', 'blue', 'green', 'cyan', 'violet']

function getRandomColorExcept(previousColor) {
  const listColorsFiltered = listColors.filter(color => color !== previousColor)
  randomColor = listColorsFiltered[Math.floor(Math.random() * listColorsFiltered.length)]
  currentColor = randomColor
  return randomColor
}

const btnElement = document.querySelector('button')
const bodyElement = document.querySelector('body')

btnElement.addEventListener('click', function() {
  bodyElement.style.backgroundColor = getRandomColorExcept(currentColor)
})