I’ve been trying to make a primitive reaction tester and tried to add a counter so it counts the amount of clicks you’ve made, but it just won’t work. Could you tell me what i did wrong?
<html>
<head>
<meta charset="utf-8">
<title>
Reaction
</title>
<style>
body {
background-color: lightgray;
margin: 0;
overflow-y: hidden;
overflow-x: hidden;
height: 100%;
width: 100%;
font: normal 10px sans-serif;
}
#screen {
position: relative;
background-color: gray;
width: 60vw;
height: 50vh;
left: 20vw;
top: 25vh;
border: solid 0.5vh dimgray;
text-align: center;
}
#screen_reaction {
position: relative;
background-color: red;
border: solid 0.1vh darkred;
width: 1vw;
height: 1vw;
left: 0;
top: 0;
}
</style>
<script>
var counter = 0;
function reaction() {
counter = document.getElementById("count").value;
counter += 1;
document.getElementById("count").value = counter
var margin = document.querySelector('#screen_reaction');
top_margin = (Math.random() * 97);
left_margin = (Math.random() * 95);
margin.style.top = `${top_margin}%`
margin.style.left = `${left_margin}%`
}
</script>
<head>
<body>
<font size="10"><a id="count" style="position: relative; left: 48vw; top: 25vh">0</a></font>
<div id="screen">
<div id="screen_reaction" onClick="reaction()">
</div>
</div>
</body>
</html>
I added var counter = 0;
thinking the code just doesnt know the variable, tried changing names, looked for errors in compilation but nothing. What’s wrong with this script?
3
Answers
You should update the line
counter = document.getElementById("count").value;
tocounter = parseInt(document.getElementById("count").innerHTML);
. Also, you should remove thevalue
attribute from thecount
element since it’s an anchor element and not an input element.i redo your code and now it can count as you wish
You need to get the value inside the tag first (.textContent)
Then you have to convert to an integer (parseInt())