Content Network

Web Development >> 2016

JavaScript Colour Mixer

By | | License: cc by-sa 4

If you are a JavaScript beginner, this is gonna excite you. The colour mixer app is really simple, yet an attractive example. First let us see it in action.

After Mixing:

How it works

It works on the principle that any colour on a computer screen is created by mixing red, green and blue in different ratios. When the three colours are mixed in the ratio 0:0:0, you get black (i.e., no colour). When you take 1:1:1, you get white. 1:0:0 will give you pure red while the mixture of red, green and no blue (i.e., 1:1:0) will give you yellow. You can mix these three colours with rational ratios also, which makes millions of colours practical.

So if you have three sliders to choose each colour component's value, you can create a new colour from those values. Now let's see the code.

The Code

    <title>Color Mixer Web App</title>
      function mix() {
        red = document.getElementById('redVal').value;
        green = document.getElementById('greenVal').value;
        blue = document.getElementById('blueVal').value;
        divMixedColor = document.getElementById('divMixedColor'); = 'rgb(' + red + ',' + green + ',' + blue + ')';
    <h1>Color Mixer Web App</h1>
      <style>label {display: inline-block; width: 4em;} </style>
      <label>Red: </label><input id='redVal' type='range' min='0' max='255' value='0' onchange='mix()' /> <br/>
      <label>Green: </label><input id='greenVal' type='range' min='0' max='255' value='0' onchange='mix()' /> <br/>
      <label>Blue: </label><input id='blueVal' type='range' min='0' max='255' value='0' onchange='mix()' /> <br/>

    <p> After Mixing: <br/>
      <div id='divMixedColor' style="width: 4em; height: 2em; background: black"></div>

In computing, normally a colour component is graded between 0 and 255. 255 means 100% (now WHITE = 255 RED, 255 GREEN, 255 BLUE). That's why we have three input sliders (input type='range') ranging from 0 to 255. Their onchange event is connected to the function mix(), which we have written in the script part. The function simply takes the sliders' values and pass them to the style property of divMixedColor (a div used to show the output colour) with the CSS function rgb(), which is used to create a colour from RGB values.

If R = 100, G = 200, and B = 255, then this will be executed: = 'rgb(100,200,255)';

How to Test the Code

Just copy the code to a text editor (such as gedit or Notepad++), save the file as an HTML file, and open it with a web browser. You're done!

Keywords (click to browse): javascript color-mixer rgb web-app web internet websites web-designing web-programming web-apps www

JavaScript Colour Mixer | Nandakumar Content Network
Copyright © 2015–2019 Nandakumar Edamana.