Velocity, Distance & Time Calculator | Premium Tool
🚀Calculate Velocity
v = d ÷ t
📏Calculate Distance
d = v × t
⏱️Calculate Time
t = d ÷ v
No calculations yet. Start calculating!
🌐 Share on Social Media
`);
printWindow.document.close();
printWindow.focus();
setTimeout(() => {
printWindow.print();
printWindow.close();
}, 250);
this.showToast('Print dialog opened!', 'success');
}showShareOptions() {
const shareSection = document.querySelector('.share-section');
shareSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
this.animateElement(shareSection, 'pulse');
this.showToast('Click any platform to share your result', 'info');
}shareOnSocial(platform) {
if (!this.resultData) {
this.showToast('Calculate something first to share!', 'error');
return;
}const shareText = `I calculated ${this.resultData.label}: ${this.resultData.value.toFixed(2)} ${this.resultData.unit} using the Velocity Distance Time Calculator!`;
const shareUrl = window.location.href;
const hashtags = 'calculator,physics,velocity';
const urls = {
facebook: `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl)}`,
x: `https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}&url=${encodeURIComponent(shareUrl)}&hashtags=${hashtags}`,
whatsapp: `https://wa.me/?text=${encodeURIComponent(shareText + ' ' + shareUrl)}`,
telegram: `https://t.me/share/url?url=${encodeURIComponent(shareUrl)}&text=${encodeURIComponent(shareText)}`,
reddit: `https://reddit.com/submit?url=${encodeURIComponent(shareUrl)}&title=${encodeURIComponent(shareText)}`,
pinterest: `https://pinterest.com/pin/create/button/?url=${encodeURIComponent(shareUrl)}&description=${encodeURIComponent(shareText)}`,
linkedin: `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(shareUrl)}`,
tiktok: `https://www.tiktok.com/upload?caption=${encodeURIComponent(shareText)}`,
vk: `https://vk.com/share.php?url=${encodeURIComponent(shareUrl)}&title=${encodeURIComponent(shareText)}`,
email: `mailto:?subject=Velocity Calculator Result&body=${encodeURIComponent(shareText + '\n\n' + shareUrl)}`
};if (urls[platform]) {
window.open(urls[platform], '_blank', 'width=600,height=400');
this.showToast(`Sharing to ${platform.charAt(0).toUpperCase() + platform.slice(1)}!`, 'success');
}
}updateURL() {
const params = new URLSearchParams();
params.set('type', this.currentType);
const inputs = document.querySelectorAll('.input-field');
inputs.forEach(input => {
if (input.value) {
params.set(input.id, input.value);
}
});const units = this.getCurrentUnits();
Object.entries(units).forEach(([key, value]) => {
params.set(`${key}Unit`, value);
});if (this.resultData) {
params.set('result', this.resultData.value.toFixed(4));
}const newUrl = `${window.location.pathname}?${params.toString()}`;
window.history.pushState({}, '', newUrl);
}handleURLParameters() {
const params = new URLSearchParams(window.location.search);
const type = params.get('type');
if (type && ['velocity', 'distance', 'time'].includes(type)) {
this.currentType = type;
// Update UI
document.querySelectorAll('.type-card').forEach(card => {
card.classList.remove('active');
if (card.dataset.type === type) {
card.classList.add('active');
}
});
this.renderInputs();
// Populate saved values
params.forEach((value, key) => {
const input = document.getElementById(key);
if (input) {
input.value = value;
}
if (key.endsWith('Unit')) {
const unitSelector = document.querySelector(`[data-input="${key.replace('Unit', '')}"]`);
if (unitSelector) {
unitSelector.textContent = value;
}
}
});
// Auto-calculate if all required fields are present
const required = this.getRequiredInputs();
const allPresent = required.every(field => {
const input = document.getElementById(field);
return input && input.value;
});
if (allPresent) {
setTimeout(() => this.calculate(), 500);
}
}
}showError(fieldId, message) {
const field = document.getElementById(fieldId);
if (field) {
field.classList.add('error');
const errorElement = document.getElementById(`${fieldId}-error`);
if (errorElement) {
errorElement.textContent = message;
}
field.addEventListener('input', () => {
field.classList.remove('error');
if (errorElement) errorElement.textContent = '';
}, { once: true });
}
}showToast(message, type = 'success') {
const toast = document.getElementById('toast');
toast.textContent = message;
toast.className = `toast show ${type}`;
setTimeout(() => {
toast.classList.remove('show');
}, 4000);
}animateElement(element, animation) {
element.style.animation = 'none';
element.offsetHeight; // Force reflow
element.style.animation = `${animation} 0.5s ease-out`;
setTimeout(() => {
element.style.animation = '';
}, 500);
}clearHistory() {
if (this.calculations.length === 0) {
this.showToast('History is already empty', 'info');
return;
}if (confirm('Are you sure you want to clear all calculation history?')) {
this.calculations = [];
this.saveHistory();
this.renderHistory();
this.showToast('History cleared successfully!', 'success');
}
}loadHistory() {
try {
const saved = localStorage.getItem('velocityCalculatorHistory');
return saved ? JSON.parse(saved) : [];
} catch (e) {
console.warn('Failed to load history:', e);
return [];
}
}saveHistory() {
try {
localStorage.setItem('velocityCalculatorHistory', JSON.stringify(this.calculations));
} catch (e) {
console.warn('Failed to save history:', e);
}
}
}// Initialize with lazy loading and performance optimizations
if ('IntersectionObserver' in window) {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// Initialize calculator when visible
window.calculator = new VelocityCalculator();
observer.disconnect();
}
});
});
observer.observe(document.querySelector('.calculator-container'));
} else {
// Fallback for older browsers
window.addEventListener('load', () => {
window.calculator = new VelocityCalculator();
});
}// Service Worker Registration for offline capability
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('data:text/javascript,' + encodeURIComponent(`
self.addEventListener('install', e => e.waitUntil(self.skipWaiting()));
self.addEventListener('activate', e => e.waitUntil(self.clients.claim()));
self.addEventListener('fetch', e => e.respondWith(fetch(e.request).catch(() => new Response('Offline'))));
`)).catch(() => {
// Silent fail - optional enhancement
});
}// Performance monitoring
if ('PerformanceObserver' in window) {
const perfObserver = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.duration > 100) {
console.warn(`Long task detected: ${entry.duration}ms`);
}
}
});
perfObserver.observe({ entryTypes: ['longtask'] });
}// Cleanup function for memory management
window.addEventListener('beforeunload', () => {
if (window.calculator) {
window.calculator.saveHistory();
}
});