Reputation: 47
I have an image with onclick
event and want to count all clicks on the image and show the total number in an input bar.
Here's a piece of code I used that didn't work
<html>
<head>
<title>Krummpleanimator</title>
<script type="text/javascript">
//imageselection
function buttonClick() {
document.getElementById('gimper').stepUp(5);
}
</script>
</head>
<body>
<div style="position: absolute; left: 10px; top: 40px;">
<img id="gimper" src="paintbrush.png" width="200" height="200" alt="gimpybutt" border="5" onclick="buttonclick();">
<input type="text" id="gimper" value="0"></input>
</div>
</body>
</html>
I expect the output to be an image that I clicked and an input bar on the side saying how many times I clicked but it just shows the image and the input bar next to it.
Could you please help me to achieve my desired result?
Upvotes: 1
Views: 2914
Reputation: 83
Use this code
your markup:
<div style="position: absolute; left: 10px; top: 40px;">
<img id="img" src="paintbrush.png" width="200" height="200" alt="gimpybutt">
<input type="text" id="gimper" value="0"></input>
</div>
JS script:
<script>
let image = document.querySelector('#img');
image.addEventListener("click", function () {
let inputValue = parseInt(document.querySelector('#gimper').value, 10);
inputValue = isNaN(inputValue) ? 0 : inputValue;
inputValue++;
document.querySelector('#gimper').value = inputValue;
})
</script>
Upvotes: 1
Reputation: 6912
First, you need to implement a function called buttonclick
that increments the value of the input.
Second, IDs are meant to be unique. Your image and input should have different IDs for document.getElementbyId
to work.
function buttonclick() {
document.getElementById("gimper").value++;
}
<body>
<div style="position: absolute; left: 10px; top: 40px;">
<img id="gimper_img" src="paintbrush.png" width="200" height="200" alt="gimpybutt" border="5" onclick="buttonclick();">
<input type="text" id="gimper" value="0"></input>
</div>
</body>
Upvotes: 6