"Unable to get property 'style' of undefined or null reference" of a defined variable.
I'm trying to make an encryption device to test my skills. I have "keys" that light up when you press a key on a keyboard, so I press "A", and "G" lights up.
I've used the debugger, all variables are fine but when the codes sets the property everything breaks on the else statement, when the timeout is over, leaving the light yellow.
I tried renaming the function incase "key" was keyword, I tried specifying "on" (which removes the errors but nothing happens), I tried switching variable x to a this.x. (sorry for horrible formatting)
<!DOCTYPE HTML>
<html>
<head>
<script>
function key(specId, on = false) {
this.elemId = specId;
this.state = on;
this.docId = document.getElementById(`${this.elemId}`);
this.blink = function() {
if(!this.state) {
this.docId.style.backgroundColor = "yellow";
this.state = true;
var x = setTimeout(this.blink, 1000);
}
else {
this.docId.style.backgroundColor = "black";
this.state = false;
}
}
}
var a = new key("keyA");
a.blink();
</script>
<style>
.key {
background-color:black;
border:1px solid #000000;
color:white;
height:36px; /* twice the size of the font */
width:36px;
border-radius:50%;
text-align:center;
}
</style>
</head>
<body>
<div id="keyA" class="key">A</div>
</body></html>
What's supposed to happen is when the window loads, the light "A" on the screen turns yellow for one second, then turns back to black. However, currently the light turns yellow, and after one second (the timeout) I get the error above.