I am manipulating the background color of 3 table cells depending on keydown
, keypress
and keyup
events.
html
<table border="1px">
<tr><th>Event</th><th>Action</th><th>Value</th></tr>
<tr><td>Keydown</td><td id="down"></td><td id="downvalue"></td></tr>
<tr><td>Keypress</td><td id="press"></td><td id="pressvalue"></td></tr>
<tr><td>Keyup</td><td id="up"></td><td id="upvalue"></td></tr>
</table>
<input type="text" id="txt" /><br />
JS
window.onload = function()
{
document.getElementById("txt").addEventListener("Keydown", keyisdown(), false);
document.getElementById("txt").addEventListener("Keyup", keyisup(), false);
document.getElementById("txt").addEventListener("Keypress", keyispress(), false);
}
function keyisdown()
{
document.getElementById("press").style.backgroundColor = "white";
document.getElementById("up").style.backgroundColor = "white";
document.getElementById("down").style.backgroundColor = "red";
}
// above function is repeated twice for keyisup and keyispress
I am supposed to type into the field, and change the background color respectively, but all run once upon page load or refresh and never again, how can i solve that? thanks.
Check this out:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
Here you have all you need to know to use addEventListener
In some old browsers this is not supported.
You can do something similar to addEventListener: