Hello. I am making a colour-picker using pure JavaScript and HTML. It consists of three HTML selects (drop downs boxes) and one div the background-colour of which will be changed by JavaScript. I am also trying to do this as "correctly" as possible. This means no Javascript code in the HTML.
My code so far looks like this:
var red = document.getElementById('red');
red.onchange = update();
var green = document.getElementById('green');
green.onchange = update();
var blue = document.getElementById('blue');
blue.onchange = update();
var thebox = document.getElementById('colourbox');
function d2h(d) {return d.toString(16);}
function h2d(h) {return parseInt(h,16);}
function update(){
finalcolor = '#' + d2h(red.value) + d2h(green.value) + d2h(blue.value)
thebox.style.background = finalcolour;
}
And the HTML looks like this:
<div id="colourbox"></div>
<form name="myform" action="colour.html">
<select name="red" id="red">
<option value="0">0</option>
.... etc etc ....
</select>
<select name="green" id="red">
<option value="0">0</option>
.... etc etc ....
</select>
<select name="blue" id="red">
<option value="0">0</option>
.... etc etc ....
</select>
</form>
The trouble is that all the document.getElementById() calls return null. Presumably because they don't exist at the time that the code is run. I have tried putting the code inside an window.onload = function() {} but a) that just gets confusing and b) I would then have to define the update function inside a function, which doesn't seem right.
Can anyone shed some light on this? Are there any general rules which might help me understand how it works? Or some documentation on the subject?
EDIT: revised code:
<script type="text/javascript">
window.onload = function(){
var red = document.getElementById('red');
red.onchange = update();
var green = document.getElementById('green');
green.onchange = update();
var blue = document.getElementById('blue');
blue.onchange = update();
var thebox = document.getElementById('colourbox');
function d2h(d) {return d.toString(16);}
function h2d(h) {return parseInt(h,16);}
function update(){
var finalcolor = '#' + d2h(document.getElementById('red').value) + d2h(document.getElementById('green').value) + d2h(document.getElementById('blue').value);
document.getElementById('colourbox').style.background = finalcolor;
}
}
</script>