简体   繁体   中英

How to insert resulting value of randomizer into html input value? (JavaScript)

I'm working on a background-gradient generator that can be manipulated by either selecting one of two HTML color inputs and choosing color manually (which is then displayed live in the background) or by clicking a "randomize" button and generating two random rgb colors to be displayed.

Github repository here.

The problem is, when you click "randomize", the value of the color input fields remains the same while the background changes. I want to make it so that the values of each random rgb color generated are then added to the inner html "value" of the input boxes so that the boxes display exactly what two colors were selected. I'm having trouble figuring out the logic of doing this.

Here is the JS of the color randomizer function if that helps:

function randomRGB() {
    var rgbValues = [];
    for(var i = 0; i < 3; i++) {
        rgbValues.push(Math.floor(Math.random() * 256));
    }
    return 'rgb(' + rgbValues[0] + ',' + rgbValues[1] + ',' + rgbValues[2] + ')';
}

function setRandom() {
    body.style.background = 'linear-gradient(to right, ' + randomRGB() + ', ' + randomRGB() + ')';
    css.textContent = body.style.background + ';';
}

And here is the HTML:

<!doctype html>
<html lang="en">
<head>
    <title>Gradient Background</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
</head>
<body id = "gradient">
    <div class="container">
        <h1>Background Generator</h1>
        <div class="inputs">
            <input class = "color1" type="color" name="color1" value="#B5DDFF">
            <input class = "color2" type="color" name="color2" value="#D998FF" id=""><br>
        </div>
        <button class="random">Randomize</button>
        <h2>Current CSS Background</h2>
        <h3></h3>
    </div>



    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script src="script.js"></script>
</body>
</html>

Please let me know if there's anything I can clarify, I'm definitely a beginner when it comes to JS and I may not have explained it in the best way.

Considering that your inputs are under a .inputs container, as I see in your github repository:

function setRandom() {
    const firstRndRGB = randomRGB();
    const secondRndRGB = randomRGB();
    const inputs = document.getElementsByClassName('inputs');

    inputs[0].value = firstRndRGB;
    inputs[1].value = secondRndRGB;
    body.style.background = 'linear-gradient(to right, ' + firstRndRGB + ', ' + secondRndRGB + ')';
    css.textContent = body.style.background + ';';
}

EDIT:

As it has to be insterted into a type="color" input, which only accepts Hex formatted colors, we must also convert the RGB format into a Hex format using regex like this:

function getHexFromRGB(x){
    return '#' + x.match(/\d+/g).map(y = z => ((+z < 16)?'0':'') + (+z).toString(16)).join('');
}

And then just do

inputs[0].value = getHexFromRGB(firstRndRGB);
inputs[1].value = getHexFromRGB(secondRndRGB);

So all you need is to use those rbg strings and convert them into hex format so you can assign them to each input's value

 function randomRGB() { var rgbValues = []; for(var i = 0; i < 3; i++) { rgbValues.push(Math.floor(Math.random() * 256)); } return 'rgb(' + rgbValues[0] + ',' + rgbValues[1] + ',' + rgbValues[2] + ')'; } function setRandom() { const firstRndRGB = randomRGB(); const secondRndRGB = randomRGB(); const inputs = document.querySelectorAll('.inputs input'); inputs[0].value = toHEX(firstRndRGB); inputs[1].value = toHEX(secondRndRGB); document.body.style.background = 'linear-gradient(to right, ' + firstRndRGB + ', ' + secondRndRGB + ')'; //css.textContent = body.style.background + ';'; } function toHEX(rgbString){ rgbString = rgbString.split("(")[1].split(")")[0]; rgbString = rgbString.split(","); rgbString = rgbString.map(x => { x = parseInt(x).toString(16); return (x.length==1) ? "0"+x : x; }); rgbString = "#"+rgbString.join(""); return rgbString; } setRandom(); document.getElementById('randomize').addEventListener('click', ()=>{ setRandom() });
 <body id = "gradient"> <div class="container"> <h1>Background Generator</h1> <div class="inputs"> <input class = "color1" type="color" name="color1"> <input class = "color2" type="color" name="color2" id=""><br> </div> <button id='randomize' class="random">Randomize</button> <h2>Current CSS Background</h2> <h3></h3> </div> </body>

MDN says that the input type="color" takes a value in lower-case hexadecimal notation. In the view there must be printed rgb value. Rename randomRGB() with randomColor() and return both of them.

function randomColor() {
    var rgb = [];
    var hex = [];
    for (var i = 0; i < 3; i++) {
        var randomColorPart = Math.floor(Math.random() * 256);
        var randomColorPartHEX = randomColorPart.toString(16);
        if (randomColorPartHEX.length < 2) {
            randomColorPartHEX = '0' + randomColorPartHEX;
        }
        rgb.push(randomColorPart);
        hex.push(randomColorPartHEX);
    }
    return {
        'rgb': 'rgb(' + rgb.join() + ')',
        'hex': '#' + hex.join(''),
    }
}

function setRandom() {
    var randomColor1 = randomColor();
    var randomColor2 = randomColor();
    var bgLinearGradient = 'linear-gradient(to right, ' + randomColor1.rgb + ', ' + randomColor2.rgb + ')';
    body.style.background = bgLinearGradient;
    css.textContent = bgLinearGradient+ ';';
    color1.value = randomColor1.hex;
    color2.value = randomColor2.hex;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM