Increase/decrease by one
These expercises show a few examples of increasing or decreasing various objects on this web page. A variable carries the value of the increment. It's important that the page remembers the most recent value of the variable. A global variable is used to do this. If a local variable is declared, the value resets to the original after every click.
Horizontal position
Click on the left and right buttons to increase/decrease the left position of this paragraph. A global variable of 30 is set to match the starting position of this paragraph. Then a function calls the variable and adds/subtracts one. Each time the function is called, one is added to the new value.
| Click the arrows to move the previous paragraph |
HTML
<h3>Horizontal position</h3>
<p id="moveMe" style="width:80%; position:relative; left:30px; border:solid;">Click on the left and right buttons to ... new value.</p>
<input type="text" id="number" value="0" size="1" />
<img src="../../images/arrow_up.png" alt="up" width="25" height="12" onclick="countIncrease()" />
<img src="../../images/arrow_down.png" alt="down" width="25" height="13" onclick="countDecrease()" />Javascript
var a=30;
function moveRight() {
a++;
document.getElementById("moveMe").style.left=a+"px";
}function moveLeft() {
a--;
document.getElementById("moveMe").style.left=a+"px";
}
Number field
Click on the up or down arrows to increase/decrease the number field. This is useful for forms or shopping carts.
HTML
<input type="text" id="number" value="0" size="1" />
<img src="../../images/arrow_up.png" alt="up" width="25" height="12" onclick="countIncrease()" />
<img src="../../images/arrow_down.png" alt="down" width="25" height="13" onclick="countDecrease()" />Javascript
var x=0
function countIncrease() {
x++;
document.getElementById("number").value=x;
}function countDecrease() {
x--;
document.getElementById("number").value=x;
}