Change Background Color using HTML, CSS and JavaScript | Project

 Change Background Color using HTML, CSS and JavaScript 




index.html file:


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Bg color</title>
</head>

<style>
    *{
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: serif;
    }

    main {
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
    }

    main p{
        font-size: 2rem;
    }

    button {
        padding: 8px;
        margin-top: 8px;
        font-size: 1rem;
        color: white;
        background: black;
        cursor: pointer;

    }
</style>

<body>
    <main>
        <h1>Change Background Color</h1>
        <p>👇</p>
        <button type="button" onclick="changeBg()">Click me!</button>
    </main>

    <script>
        // const colorArr = ['red', 'green', 'blue', 'yellow', 'purple', 'orange', 'brown', 'black', 'aqua', 'fuchsia', 'gray', 'lime', 'maroon', 'navy', 'olive', 'silver', 'teal', 'white', 'yellow', 'aliceblue', 'antiquewhite', 'aquamarine', 'yellowgreen'];

        const changeBg = () => {
            // const colorName = colorArr[Math.floor(Math.random() * colorArr.length)];
            const colorName = Math.floor(Math.random()*16777215).toString(16);
            document.body.style.backgroundColor = '#' + colorName;
        }
    </script>
</body>

</html>

Change Background color by hover the mouse:


<body>
    <main onmousemove="changeBg(event)">
        <h1>Change Background Color</h1>
    </main>

    <script>
        const changeBg = (event) => {
            let x = event.clientX;
            let y = event.clientY;
            let z = event.screenY;
            document.body.style.backgroundColor = `rgb(${y}, ${x}, ${z})`;
        }
    </script>
</body>


Post a Comment

0 Comments