Today I will show you how to build a tiny x and y tracker in JS
class PositionCounter {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
// Move the position by dx and dy
move(dx, dy) {
this.x += dx;
this.y += dy;
return this; // Allow method chaining
}
// Reset position to (0, 0)
reset() {
this.x = 0;
this.y = 0;
return this; // Allow method chaining
}
// Display current position
display() {
console.log(`Current Position: X = ${this.x}, Y = ${this.y}`);
return this; // Allow method chaining
}
// Get current position as an object
getPosition() {
return { x: this.x, y: this.y };
}
}
// Example usage:
const counter = new PositionCounter();
counter.move(5, 3).display(); // Move and display
counter.move(-2, 7).display(); // Move again and display
counter.reset().display(); // Reset and display
// Or get position without displaying:
const currentPos = counter.move(10, 20).getPosition();
console.log('Current position:', currentPos);
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Position Counter Demo</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
button { margin: 5px; padding: 8px 12px; }
#output { margin-top: 20px; padding: 10px; border: 1px solid #ccc; }
</style>
</head>
<body>
<h1>Position Counter</h1>
<div>
<button onclick="move(1, 0)">Move Right (+X)</button>
<button onclick="move(-1, 0)">Move Left (-X)</button>
<button onclick="move(0, 1)">Move Down (+Y)</button>
<button onclick="move(0, -1)">Move Up (-Y)</button>
<button onclick="reset()">Reset</button>
</div>
<div id="output">Position: X=0, Y=0</div>
<script>
const counter = new PositionCounter();
const output = document.getElementById('output');
function updateDisplay() {
output.textContent = `Position: X=${counter.x}, Y=${counter.y}`;
}
function move(dx, dy) {
counter.move(dx, dy);
updateDisplay();
}
function reset() {
counter.reset();
updateDisplay();
}
// The PositionCounter class from above would go here
class PositionCounter {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
move(dx, dy) {
this.x += dx;
this.y += dy;
return this;
}
reset() {
this.x = 0;
this.y = 0;
return this;
}
}
</script>
</body>
</html>