Accelerometer UI Components utility

Ready-to-use JavaScript components with copyable code

you are here
🎮 Live Demo
Horizontal (X)
0.00
Vertical (Y)
0.00
Acceleration Vector
(0.00, 0.00)
0° UP
Ready
💻 Component Code
// HORIZONTAL ACCELEROMETER COMPONENT
// Usage: const xAccel = new HorizontalAccelerometer('knobId', 'trackId', 'valueId');

class HorizontalAccelerometer {
    constructor(knobId, trackId, valueId) {
        this.knob = document.getElementById(knobId);
        this.track = document.getElementById(trackId);
        this.valueDisplay = document.getElementById(valueId);
        
        this.value = 0;
        this.velocity = 0;
        this.isDragging = false;
        this.startX = 0;
        this.startValue = 0;
        
        this.init();
    }
    
    init() {
        this.knob.addEventListener('mousedown', (e) => this.startDrag(e.clientX));
        this.knob.addEventListener('touchstart', (e) => {
            e.preventDefault();
            this.startDrag(e.touches[0].clientX);
        });
        
        document.addEventListener('mousemove', (e) => {
            if (this.isDragging) this.drag(e.clientX);
        });
        
        document.addEventListener('touchmove', (e) => {
            if (this.isDragging && e.touches[0]) {
                e.preventDefault();
                this.drag(e.touches[0].clientX);
            }
        }, { passive: false });
        
        document.addEventListener('mouseup', () => this.stopDrag());
        document.addEventListener('touchend', () => this.stopDrag());
    }
    
    startDrag(clientX) {
        this.isDragging = true;
        this.startX = clientX;
        this.startValue = this.value;
        this.velocity = 0;
        this.updateTrackColor();
    }
    
    drag(clientX) {
        const delta = (clientX - this.startX) / 80;
        this.value = Math.max(-1, Math.min(1, this.startValue + delta));
        this.velocity = (this.value - this.startValue) * 0.3;
        this.update();
    }
    
    stopDrag() {
        this.isDragging = false;
        this.updateTrackColor();
    }
    
    update() {
        this.knob.style.left = `${85 + this.value * 80}px`;
        this.valueDisplay.textContent = this.value.toFixed(2);
        this.updateTrackColor();
    }
    
    updateTrackColor() {
        const intensity = Math.abs(this.value);
        const velocityIntensity = Math.abs(this.velocity);
        
        if (this.isDragging) {
            this.track.style.background = `rgba(0, 180, 216, ${0.3 + intensity * 0.4})`;
        } else if (velocityIntensity > 0.05) {
            this.track.style.background = `rgba(0, 180, 216, ${0.2 + velocityIntensity * 0.3})`;
        } else {
            this.track.style.background = `rgba(255, 255, 255, ${0.05 + intensity * 0.05})`;
        }
    }
    
    updatePhysics() {
        if (!this.isDragging) {
            const springForce = -this.value * 0.2;
            this.velocity += springForce;
            this.velocity *= 0.9;
            this.value += this.velocity * 0.1;
            
            if (Math.abs(this.value) < 0.005 && Math.abs(this.velocity) < 0.005) {
                this.value = this.velocity = 0;
            }
            
            this.update();
        }
        
        return this.value;
    }
    
    setValue(newValue) {
        this.value = Math.max(-1, Math.min(1, newValue));
        this.velocity = 0;
        this.update();
    }
}
📦 Installation & Usage
Step 1: Include Components
Copy the component classes you need into your project. Each component is standalone and only requires vanilla JavaScript.
Step 2: HTML Structure
Create HTML elements with matching IDs. The components will automatically attach to these elements.
Step 3: Initialize
Instantiate the components and start the animation loop. Components handle their own physics and rendering.
Step 4: Use Values
Access acceleration values from the components. Values range from -1 to 1 on each axis.
🚀 Usage Examples
Basic Setup
// 1. Create components
const xAccel = new HorizontalAccelerometer('hKnob', 'hTrack', 'xValue');
const yAccel = new VerticalAccelerometer('vKnob', 'vTrack', 'yValue');
const result = new ResultDisplay();

// 2. Animation loop
function animate() {
    const x = xAccel.updatePhysics();
    const y = yAccel.updatePhysics();
    result.update(x, y, xAccel.isDragging || yAccel.isDragging);
    requestAnimationFrame(animate);
}
animate();

// 3. Get current values anytime
console.log(`X: ${xAccel.value}, Y: ${yAccel.value}`);
Game Controller Example
// Game controller using accelerometer values
class GameController {
    constructor() {
        this.xAccel = new HorizontalAccelerometer('xCtrl', 'xTrack', 'xDisplay');
        this.yAccel = new VerticalAccelerometer('yCtrl', 'yTrack', 'yDisplay');
        this.player = { x: 0, y: 0 };
        this.animate();
    }

    animate() {
        // Get acceleration values (-1 to 1)
        const accelX = this.xAccel.updatePhysics();
        const accelY = this.yAccel.updatePhysics();

        // Apply to player position (with some scaling)
        this.player.x += accelX * 5;
        this.player.y += accelY * 5;

        // Keep player in bounds
        this.player.x = Math.max(-100, Math.min(100, this.player.x));
        this.player.y = Math.max(-100, Math.min(100, this.player.y));

        // Update game
        this.updateGame();
        requestAnimationFrame(() => this.animate());
    }

    updateGame() {
        // Your game logic here
        document.getElementById('player').style.transform = 
            `translate(${this.player.x}px, ${this.player.y}px)`;
    }
}

// Start the game
const game = new GameController();
Programmatic Control
// You can also set values programmatically
const accel = new HorizontalAccelerometer('knob', 'track', 'value');

// Set specific value (-1 to 1)
accel.setValue(0.5);  // Move to right position

// Simulate a "bump"
setTimeout(() => {
    accel.setValue(-0.3);  // Move to left position
}, 1000);

// Reset to center
setTimeout(() => {
    accel.setValue(0);  // Return to center
}, 2000);

// Listen for changes
const observer = {
    update: (x, y) => {
        console.log(`Acceleration changed: X=${x.toFixed(2)}, Y=${y.toFixed(2)}`);
        // Update your application state here
    }
};
@yus at yusdesign