Java Script 1: Color Mixer

Java Script 1: Color Mixer

Since I decided to learn JavaScript I also made my daily exercise about that. Next you see what I got from ChatGPT, and as always my code is below 😄⬇️

Exercise: Create a Digital Color Mixer

Imagine you're creating a basic digital color mixer. This exercise will help you understand variables, user input, and basic functions in JavaScript.

  1. Objective: Allow the user to input three primary colors (Red, Green, Blue) in varying intensities (0 to 255) and display the resulting color.

  2. Steps:

    • Create three variables to store the values for Red, Green, and Blue.

    • Use prompt dialogs to let the user input values for each color (make sure they are numbers between 0 and 255).

    • Combine these values to create a final color (you'll later learn this is done through CSS or canvas in HTML).

    • Display the resulting color to the user. For a start, you could just console.log the final color in RGB format (e.g., "rgb(255, 100, 50)").

  3. Challenges:

    • Add validation to ensure that the user inputs numbers only within the 0-255 range.

    • Try to show the resulting color in a more visual way (this might require some HTML and CSS).

My Code

On my own I was able to define the variables and console.log the result.

The function and then background color change is still from ChatGPT, but looks all very logical to me so I should be able to get a better grasp of it soon enough 😊

Will need to see if I can get used to do…while, as I never used this kind of concept in Python

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

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

<body>
    <script>
        // Function to get valid color input
        function getColorInput(colorName) {
            let color;
            do {
                color = parseInt(prompt(`Enter a value for ${colorName} (0-255): `), 10);
            } while (isNaN(color) || color < 0 || color > 255);
            return color;
        }

        // Initializing color variables
        let red = getColorInput('Red');
        let green = getColorInput('Green');
        let blue = getColorInput('Blue');

        // Creating the RGB color string
        let rgbColor = `rgb(${red}, ${green}, ${blue})`;

        // Displaying results in the console
        console.log(rgbColor);

        // Changing the background color of the body
        document.body.style.backgroundColor = rgbColor;
    </script>
</body>
</html>