Ok so, what I need to do is change some numbers on the screen when keys are pressed, i have it working but I'm not happy with it.
I have a input field and a div that is being updated when the value of the input filed changes. I did that so that I would not be constrained by the input field's blinking carat etc. I don't want to display the input field at all but when I hide it with CSS or type="hidden" it no longer works. I was trying to get this working with JS variables but so far have been unsuccessful.
Any ideas?
HTML
<html>
<head>
<link rel="stylesheet" type="text/css" href="number.css" />
</head>
<body onLoad="focus();myText.focus();changeNumber()">
<div id='number'>
</div>
<input type="text" id="myText" value="1"/>
</body>
<footer>
<script type="text/javascript" src="number.js"></script>
</footer>
</html>
JAVASCRIPT
var myText = document.getElementById("myText");
function changeNumber(){
var userInput = document.getElementById('myText').value;
document.getElementById('number').innerHTML = userInput;
}
// Capture keyDown events
myText.onkeydown = function(e) {
// "34" is the up arrow key
if (e.keyCode == 34) {
// increment the value in the text input
myText.value++;
changeNumber()
// "33" is the down arrow key
} else if (e.keyCode == 33 && myText.value > 1) {
// decrement the value in the text input
myText.value--;
changeNumber()
}
}
HERE IN THE FINAL FIXED CODE * THANKS GUYS! **
HTML
<html>
<head>
<link rel="stylesheet" type="text/css" href="number.css" />
</head>
<body onLoad="focus();number.focus();changeNumber()">
<div id='number' value="1">
</div>
</body>
<footer>
<script type="text/javascript" src="number.js"></script>
</footer>
</html>
JAVASCRIPT
var i = parseInt(1);
function changeNumber(){
var userInput = i;
document.getElementById('number').innerHTML = userInput;
}
// Capture keyDown events for document
document.onkeydown = function(e) {
// "34" is the PGUp key
if (e.keyCode == 34) {
// increment the value in the text input
(i++);
changeNumber()
// "33" is the PGDown key
} else if (e.keyCode == 33 && i > 1) {
// decrement the value in the text input
(i--);
changeNumber()
}
// "66" is the b key
if (e.keyCode == 66){
window.location.reload()
}
}
The problem with your code is this:
myText.value--;
and
myText.value++;
myText
is a DOM element, and the value
property has a string, not an integer, I'd recommend doing:
var i = parseInt(myText.value);
myText.value = (i++);