Last Updated: February 25, 2016
·
2.027K
· ivex

A simple gradient in Javascript

How to do a simple gradient:

Create a simple html page with 2 textareas:

<!doctype html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css"><!-- The css stylesheet -->
    </head>
    <body>
        <form method="post" id="id">
            <textarea id="code" class="code" placeholder="Your code" onkeyup="replace();"></textarea><br/><!-- After a key press, the replace() function will be launched -->
            <textarea id="replaceDiv" class="code" placeholder="Your code"></textarea><br/>
        </form>
        <script type="text/javascript" src="script.js"></script><!-- The script, will be added later -->
    </body>
</html>

Then we add a simple css code

html {position:relative;min-height:100%;}
body {margin:0 0 70px;}

form{text-align: center;}
.code{max-width: 1000px;width: 500px;height: 200px;background-color: #34495e;color: #FFF}
#replaceDiv{color: #000;background-color: #FFF;}
.submitCode{background-color:#2980b9;border: 1px solid #FFF;border-radius: 5px;height:     30px;color: #FFF;transition: background-color .3s ease-out;}
.submitCode:hover{background-color: #2c3e50}

So you got a thing like that:

alt text

And then, the javascript code:

function replace(){
    var txtArea = document.getElementById('code').value.length; // The length of the first textarea
    document.getElementById('replaceDiv').value = document.getElementById('code').value;
    var backColor = (255-txtArea); //This line replace the value of the second textarea by the first one 
    if (txtArea <= 255) {
        document.getElementById('replaceDiv').style.color = 'rgb(' + txtArea + ',' + txtArea + ',' +   txtArea + ')';
        document.getElementById('replaceDiv').style.backgroundColor = 'rgb(' + backColor + ',' + backColor + ',' + backColor + ')';
        //Those lines are doing the first gradient, when txtArea is under 255
    }
    else if(txtArea >= 255) {
        var txtArea2 = (txtArea-255)
        var txtColor = (255-txtArea2)
        document.getElementById('replaceDiv').style.color = 'rgb(' + txtColor + ',' + txtColor + ',' + txtColor + ')';
        document.getElementById('replaceDiv').style.backgroundColor = 'rgb(' + txtArea2 + ',' + txtArea2 + ',' + txtArea2 + ')';
        //Those lines are doing the second gradient, when txtArea is under 255
    }
}

And then, you'll get a gradient in terms of the length of the first textarea's value.

Thanks for reading, and happy coding !

NB: I'm a french developper, so please excuse my bad english level, hope you like it nevertheless :)