TransWikia.com

Clicking a button and getting a different color with each click in JavaScript

Stack Overflow Asked by Zoh on January 3, 2022

How can I merge these two functions into one that changes color to a random color with each button click without reloading the page?

HTML File

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
    <title>change-color</title>
</head>
<body id="body">
    <button id="button">Click Me</button>
    <button id="button-two">Click to clear</button>
    <script src="scripts/index.js"></script>
</body>
</html>

JS File

const btn = document.querySelector('#button')
const btnTwo = document.querySelector('#button-two')
const rst = document.querySelector('#reset')
const body = document.querySelector('#body')
randomNumber = Math.floor((Math.random() * 10000) - 5)



const clear = () => {
    btnTwo.addEventListener('click', (e) => {
        body.style.backgroundColor = 'white' 
        location.reload();
    }) 
    
}


const change = () => {
    btn.addEventListener('click', (e) => {
        body.style.backgroundColor = `#${randomNumber}`  
    })  
    return clear()
}

change()

One Answer

Just generate a new random number on each click instead of only on page load.

const change = () => {
    btn.addEventListener('click', (e) => {
        let randomNumber = Math.floor((Math.random() * 10000) - 5);
        body.style.backgroundColor = `#${randomNumber}`  
    })  
}

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
    <title>change-color</title>
</head>
<body id="body">
    <button id="button">Click Me</button>
    <script>
const btn = document.querySelector('#button')
const btnTwo = document.querySelector('#button-two')
const rst = document.querySelector('#reset')
const body = document.querySelector('#body')


const change = () => {
    btn.addEventListener('click', (e) => {
        let randomNumber = Math.floor((Math.random() * 10000) - 5);
        body.style.backgroundColor = `#${randomNumber}`  
    })  
}

change()
    </script>
</body>
</html>

Answered by Unmitigated on January 3, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP