HTML & JS Topic
JavaScript Timing & Browser APIs
1. setTimeout & setInterval
setTimeout - Execute Once After Delay
javascript
// Basic syntax
setTimeout(callbackFunction, delayInMilliseconds);
// Example 1: Simple timeout
setTimeout(() => {
console.log('This runs after 2 seconds');
}, 2000);
// Example 2: With named function
function showMessage() {
console.log('Hello after 3 seconds!');
}
setTimeout(showMessage, 3000);
// Example 3: Passing parameters
function greet(name, message) {
console.log(`${message}, ${name}!`);
}
setTimeout(greet, 1000, 'Alice', 'Welcome'); // Parameters after delay
// Example 4: Store timeout ID for cancellation
const timeoutId = setTimeout(() => {
console.log('This will be cancelled');
}, 5000);
// Cancel the timeout
clearTimeout(timeoutId);
console.log('Timeout cancelled');
setInterval - Execute Repeatedly
javascript
// Basic syntax
setInterval(callbackFunction, intervalInMilliseconds);
// Example 1: Simple interval
let counter = 0;
const intervalId = setInterval(() => {
counter++;
console.log(`Tick ${counter}`);
if (counter >= 5) {
clearInterval(intervalId);
console.log('Interval stopped');
}
}, 1000);
// Example 2: Updating UI
let seconds = 0;
const timerDisplay = document.getElementById('timer');
const timerId = setInterval(() => {
seconds++;
timerDisplay.textContent = `Time: ${seconds}s`;
if (seconds >= 60) {
clearInterval(timerId);
timerDisplay.textContent = 'Time\'s up!';
}
}, 1000);
// Example 3: Slide show
let currentSlide = 0;
const slides = ['slide1.jpg', 'slide2.jpg', 'slide3.jpg'];
const slideElement = document.getElementById('slide');
const slideShow = setInterval(() => {
currentSlide = (currentSlide + 1) % slides.length;
slideElement.src = slides[currentSlide];
console.log(`Showing slide: ${slides[currentSlide]}`);
}, 3000);
// Stop after 30 seconds
setTimeout(() => {
clearInterval(slideShow);
console.log('Slide show ended');
}, 30000);
Practical Examples
Countdown Timer
html
<div class="countdown">
<h2>Countdown Timer</h2>
<div id="countdown-display">10</div>
<button onclick="startCountdown()">Start Countdown</button>
<button onclick="resetCountdown()">Reset</button>
</div>
<script>
let countdownInterval;
let timeLeft = 10;
function startCountdown() {
clearInterval(countdownInterval); // Clear any existing interval
const display = document.getElementById('countdown-display');
timeLeft = 10;
display.textContent = timeLeft;
display.style.color = 'black';
countdownInterval = setInterval(() => {
timeLeft--;
display.textContent = timeLeft;
if (timeLeft <= 3) {
display.style.color = 'red';
display.style.fontSize = '2em';
}
if (timeLeft <= 0) {
clearInterval(countdownInterval);
display.textContent = 'TIME\'S UP!';
display.style.color = 'red';
display.style.fontSize = '3em';
// Play sound or show alert
setTimeout(() => {
alert('Time is up!');
}, 100);
}
}, 1000);
}
function resetCountdown() {
clearInterval(countdownInterval);
const display = document.getElementById('countdown-display');
timeLeft = 10;
display.textContent = timeLeft;
display.style.color = 'black';
display.style.fontSize = '1em';
}
</script>
<style>
.countdown {
text-align: center;
padding: 20px;
border: 2px solid #333;
border-radius: 10px;
max-width: 300px;
margin: 20px auto;
}
#countdown-display {
font-size: 4em;
font-weight: bold;
margin: 20px 0;
transition: all 0.3s ease;
}
button {
padding: 10px 20px;
margin: 5px;
font-size: 16px;
cursor: pointer;
}
</style>
Typing Effect Animation
html
<div class="typing-effect">
<h2>Typing Effect</h2>
<div id="typed-text"></div>
<div id="cursor">|</div>
<button onclick="startTyping()">Start Typing</button>
<button onclick="resetTyping()">Reset</button>
</div>
<script>
let typingInterval;
let text = "Hello! Welcome to JavaScript Timing APIs. Let's learn setTimeout and setInterval!";
let index = 0;
let isTyping = false;
function startTyping() {
if (isTyping) return;
isTyping = true;
const typedText = document.getElementById('typed-text');
const cursor = document.getElementById('cursor');
typedText.textContent = '';
index = 0;
// Blinking cursor effect
const cursorInterval = setInterval(() => {
cursor.style.visibility = cursor.style.visibility === 'hidden' ? 'visible' : 'hidden';
}, 500);
// Typing effect
typingInterval = setInterval(() => {
if (index < text.length) {
typedText.textContent += text.charAt(index);
index++;
} else {
clearInterval(typingInterval);
clearInterval(cursorInterval);
cursor.style.visibility = 'visible';
isTyping = false;
}
}, 50); // Speed of typing
// Auto reset after completion
setTimeout(() => {
if (isTyping) return;
setTimeout(resetTyping, 2000);
}, text.length * 50 + 2000);
}
function resetTyping() {
clearInterval(typingInterval);
document.getElementById('typed-text').textContent = '';
document.getElementById('cursor').style.visibility = 'visible';
isTyping = false;
}
</script>
<style>
.typing-effect {
padding: 20px;
border: 2px solid #333;
border-radius: 10px;
max-width: 600px;
margin: 20px auto;
font-family: monospace;
}
#typed-text, #cursor {
display: inline;
font-size: 1.2em;
min-height: 1.5em;
}
#cursor {
font-weight: bold;
animation: blink 1s infinite;
}
@keyframes blink {
0%, 50% { opacity: 1; }
51%, 100% { opacity: 0; }
}
</style>
2. LocalStorage & SessionStorage
LocalStorage - Persistent Storage
javascript
// Set item
localStorage.setItem('username', 'john_doe');
localStorage.setItem('theme', 'dark');
localStorage.setItem('userPreferences', JSON.stringify({
language: 'en',
notifications: true,
fontSize: 'medium'
}));
// Get item
const username = localStorage.getItem('username');
console.log(username); // 'john_doe'
const preferences = JSON.parse(localStorage.getItem('userPreferences'));
console.log(preferences.language); // 'en'
// Remove item
localStorage.removeItem('theme');
// Clear all
localStorage.clear();
// Check if key exists
if (localStorage.getItem('username')) {
console.log('User is logged in');
}
// Get key by index
const firstKey = localStorage.key(0);
// Get number of items
const itemCount = localStorage.length;
// Iterate through all items
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
console.log(`${key}: ${value}`);
}
SessionStorage - Temporary Session Storage
javascript
// Same API as localStorage, but clears when tab closes
sessionStorage.setItem('sessionId', 'abc123xyz');
sessionStorage.setItem('cartItems', JSON.stringify(['item1', 'item2']));
const sessionId = sessionStorage.getItem('sessionId');
console.log(sessionId); // 'abc123xyz'
// Remove after 30 minutes (simulated)
setTimeout(() => {
sessionStorage.removeItem('sessionId');
}, 30 * 60 * 1000);
Practical Storage Examples
Theme Preference Saver
html
<div class="theme-manager">
<h2>Theme Preference</h2>
<div class="theme-options">
<button onclick="setTheme('light')">Light Theme</button>
<button onclick="setTheme('dark')">Dark Theme</button>
<button onclick="setTheme('blue')">Blue Theme</button>
</div>
<p>Current theme: <span id="current-theme">light</span></p>
<button onclick="clearTheme()">Clear Saved Theme</button>
</div>
<script>
// Load saved theme on page load
document.addEventListener('DOMContentLoaded', () => {
const savedTheme = localStorage.getItem('theme') || 'light';
applyTheme(savedTheme);
document.getElementById('current-theme').textContent = savedTheme;
});
function setTheme(themeName) {
// Save to localStorage
localStorage.setItem('theme', themeName);
// Apply theme
applyTheme(themeName);
// Update display
document.getElementById('current-theme').textContent = themeName;
// Show confirmation
showMessage(`Theme changed to ${themeName}`);
}
function applyTheme(themeName) {
const body = document.body;
// Remove all theme classes
body.classList.remove('light-theme', 'dark-theme', 'blue-theme');
// Add selected theme class
body.classList.add(`${themeName}-theme`);
}
function clearTheme() {
localStorage.removeItem('theme');
applyTheme('light');
document.getElementById('current-theme').textContent = 'light';
showMessage('Theme preference cleared');
}
function showMessage(text) {
const message = document.createElement('div');
message.textContent = text;
message.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: #4CAF50;
color: white;
padding: 10px 20px;
border-radius: 5px;
z-index: 1000;
`;
document.body.appendChild(message);
setTimeout(() => {
message.remove();
}, 3000);
}
</script>
<style>
.light-theme {
background-color: #ffffff;
color: #333333;
}
.dark-theme {
background-color: #333333;
color: #ffffff;
}
.blue-theme {
background-color: #e3f2fd;
color: #1565c0;
}
.theme-manager {
padding: 20px;
border-radius: 10px;
margin: 20px auto;
max-width: 500px;
text-align: center;
}
.theme-options button {
padding: 10px 20px;
margin: 5px;
font-size: 16px;
cursor: pointer;
border: none;
border-radius: 5px;
}
.light-theme .theme-options button {
background: #f0f0f0;
color: #333;
}
.dark-theme .theme-options button {
background: #555;
color: white;
}
.blue-theme .theme-options button {
background: #bbdefb;
color: #0d47a1;
}
</style>
Shopping Cart with LocalStorage
html
<div class="shopping-cart">
<h2>🛒 Shopping Cart</h2>
<div class="products">
<div class="product" data-id="1" data-name="Laptop" data-price="999">
<h3>Laptop - $999</h3>
<button onclick="addToCart(1)">Add to Cart</button>
</div>
<div class="product" data-id="2" data-name="Mouse" data-price="25">
<h3>Mouse - $25</h3>
<button onclick="addToCart(2)">Add to Cart</button>
</div>
<div class="product" data-id="3" data-name="Keyboard" data-price="75">
<h3>Keyboard - $75</h3>
<button onclick="addToCart(3)">Add to Cart</button>
</div>
</div>
<div class="cart-section">
<h3>Your Cart (<span id="cart-count">0</span> items)</h3>
<div id="cart-items"></div>
<p>Total: $<span id="cart-total">0</span></p>
<button onclick="clearCart()">Clear Cart</button>
<button onclick="checkout()">Checkout</button>
</div>
</div>
<script>
// Load cart from localStorage on page load
document.addEventListener('DOMContentLoaded', () => {
loadCart();
updateCartDisplay();
});
// Cart data structure
let cart = [];
function loadCart() {
const savedCart = localStorage.getItem('shoppingCart');
if (savedCart) {
cart = JSON.parse(savedCart);
}
}
function saveCart() {
localStorage.setItem('shoppingCart', JSON.stringify(cart));
}
function addToCart(productId) {
const productElement = document.querySelector(`[data-id="${productId}"]`);
const name = productElement.dataset.name;
const price = parseFloat(productElement.dataset.price);
// Check if product already in cart
const existingItem = cart.find(item => item.id === productId);
if (existingItem) {
existingItem.quantity++;
} else {
cart.push({
id: productId,
name: name,
price: price,
quantity: 1
});
}
saveCart();
updateCartDisplay();
showNotification(`${name} added to cart!`);
}
function updateCartDisplay() {
const cartItemsElement = document.getElementById('cart-items');
const cartCountElement = document.getElementById('cart-count');
const cartTotalElement = document.getElementById('cart-total');
// Clear current display
cartItemsElement.innerHTML = '';
// Update items
let total = 0;
let itemCount = 0;
cart.forEach(item => {
itemCount += item.quantity;
total += item.price * item.quantity;
const itemElement = document.createElement('div');
itemElement.className = 'cart-item';
itemElement.innerHTML = `
<span>${item.name} x${item.quantity}</span>
<span>$${(item.price * item.quantity).toFixed(2)}</span>
<button onclick="removeFromCart(${item.id})">Remove</button>
`;
cartItemsElement.appendChild(itemElement);
});
// Update totals
cartCountElement.textContent = itemCount;
cartTotalElement.textContent = total.toFixed(2);
}
function removeFromCart(productId) {
const itemIndex = cart.findIndex(item => item.id === productId);
if (itemIndex !== -1) {
const item = cart[itemIndex];
if (item.quantity > 1) {
item.quantity--;
} else {
cart.splice(itemIndex, 1);
}
saveCart();
updateCartDisplay();
showNotification(`Item removed from cart`);
}
}
function clearCart() {
if (cart.length === 0) {
showNotification('Cart is already empty');
return;
}
if (confirm('Are you sure you want to clear your cart?')) {
cart = [];
localStorage.removeItem('shoppingCart');
updateCartDisplay();
showNotification('Cart cleared');
}
}
function checkout() {
if (cart.length === 0) {
showNotification('Your cart is empty!');
return;
}
const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
alert(`Checkout complete! Total: $${total.toFixed(2)}\nThank you for your purchase!`);
// Clear cart after checkout
cart = [];
localStorage.removeItem('shoppingCart');
updateCartDisplay();
}
function showNotification(message) {
const notification = document.createElement('div');
notification.textContent = message;
notification.style.cssText = `
position: fixed;
bottom: 20px;
right: 20px;
background: #4CAF50;
color: white;
padding: 10px 20px;
border-radius: 5px;
z-index: 1000;
animation: slideIn 0.3s ease;
`;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOut 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 2000);
}
// Add CSS for animations
const style = document.createElement('style');
style.textContent = `
@keyframes slideIn {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes slideOut {
from { transform: translateX(0); opacity: 1; }
to { transform: translateX(100%); opacity: 0; }
}
`;
document.head.appendChild(style);
</script>
<style>
.shopping-cart {
max-width: 800px;
margin: 20px auto;
padding: 20px;
border: 2px solid #ddd;
border-radius: 10px;
}
.products {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.product {
padding: 15px;
border: 1px solid #ccc;
border-radius: 8px;
text-align: center;
}
.product button {
padding: 8px 16px;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.cart-section {
padding: 20px;
background: #f9f9f9;
border-radius: 8px;
}
.cart-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
border-bottom: 1px solid #eee;
}
.cart-item button {
padding: 4px 8px;
background: #ff4444;
color: white;
border: none;
border-radius: 3px;
cursor: pointer;
}
.cart-section > button {
margin: 10px 5px 0 0;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.cart-section > button:first-of-type {
background: #ff4444;
color: white;
}
.cart-section > button:last-of-type {
background: #4CAF50;
color: white;
}
</style>
3. Window & Document Objects
Window Object - Browser Window API
javascript
// Window dimensions
console.log('Window width:', window.innerWidth);
console.log('Window height:', window.innerHeight);
console.log('Screen width:', window.screen.width);
console.log('Screen height:', window.screen.height);
// Navigation
window.location.href = 'https://example.com'; // Navigate to URL
console.log('Current URL:', window.location.href);
console.log('Hostname:', window.location.hostname);
console.log('Path:', window.location.pathname);
console.log('Query params:', window.location.search);
// History
window.history.back(); // Go back
window.history.forward(); // Go forward
window.history.go(-2); // Go back 2 pages
// Open new window
const newWindow = window.open('https://example.com', '_blank', 'width=600,height=400');
setTimeout(() => newWindow.close(), 5000); // Close after 5 seconds
// Scroll
window.scrollTo(0, 100); // Scroll to position
window.scrollTo({ top: 0, behavior: 'smooth' }); // Smooth scroll to top
// Alert, Confirm, Prompt
window.alert('Hello World!');
const confirmed = window.confirm('Are you sure?');
if (confirmed) {
console.log('User clicked OK');
}
const name = window.prompt('What is your name?', 'Guest');
console.log('User entered:', name);
// Timers (global, same as setTimeout/setInterval)
const timerId = window.setTimeout(() => console.log('Timeout'), 1000);
window.clearTimeout(timerId);
// LocalStorage & SessionStorage (also on window)
window.localStorage.setItem('key', 'value');
window.sessionStorage.setItem('session', 'data');
// Event listeners on window
window.addEventListener('resize', () => {
console.log(`Window resized to: ${window.innerWidth}x${window.innerHeight}`);
});
window.addEventListener('scroll', () => {
console.log('Scroll position:', window.scrollY);
});
window.addEventListener('beforeunload', (event) => {
// Show confirmation before leaving
event.preventDefault();
event.returnValue = '';
return 'Are you sure you want to leave? Changes may not be saved.';
});
// Online/offline detection
window.addEventListener('online', () => {
console.log('You are online!');
document.body.classList.remove('offline');
});
window.addEventListener('offline', () => {
console.log('You are offline!');
document.body.classList.add('offline');
});
Document Object - Page Content API
javascript
// Document properties
console.log('Title:', document.title);
document.title = 'New Page Title'; // Change page title
console.log('URL:', document.URL);
console.log('Domain:', document.domain);
console.log('Character set:', document.characterSet);
// Document elements
console.log('Body:', document.body);
console.log('Head:', document.head);
console.log('HTML element:', document.documentElement);
console.log('Forms:', document.forms);
console.log('Images:', document.images);
console.log('Links:', document.links);
// Create and modify elements
const newDiv = document.createElement('div');
newDiv.textContent = 'Hello World';
newDiv.id = 'myDiv';
newDiv.className = 'container';
document.body.appendChild(newDiv);
// Query elements
const element = document.getElementById('myDiv');
const elements = document.getElementsByClassName('container');
const firstPara = document.querySelector('p');
const allButtons = document.querySelectorAll('button');
// Document events
document.addEventListener('DOMContentLoaded', () => {
console.log('DOM fully loaded and parsed');
});
document.addEventListener('click', (event) => {
console.log('Clicked on:', event.target);
});
// Document methods
document.write('<h1>Hello World</h1>'); // Warning: Overwrites document if used after load
// Document styles
document.body.style.backgroundColor = 'lightblue';
document.documentElement.style.setProperty('--primary-color', 'blue');
// Cookies
document.cookie = 'username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/';
console.log('Cookies:', document.cookie);
Practical Window & Document Examples
Responsive Layout Manager
html
<div class="layout-manager">
<h2>Window & Document Info</h2>
<div class="info-grid">
<div class="info-card">
<h3>Window Size</h3>
<p>Width: <span id="window-width">-</span>px</p>
<p>Height: <span id="window-height">-</span>px</p>
</div>
<div class="info-card">
<h3>Scroll Position</h3>
<p>X: <span id="scroll-x">-</span>px</p>
<p>Y: <span id="scroll-y">-</span>px</p>
</div>
<div class="info-card">
<h3>Document Info</h3>
<p>Title: <span id="doc-title">-</span></p>
<p>URL: <span id="doc-url">-</span></p>
</div>
<div class="info-card">
<h3>Online Status</h3>
<p>Status: <span id="online-status">-</span></p>
<p>Last Online: <span id="last-online">-</span></p>
</div>
</div>
<div class="controls">
<button onclick="scrollToTop()">Scroll to Top</button>
<button onclick="scrollToBottom()">Scroll to Bottom</button>
<button onclick="openPopup()">Open Popup</button>
<button onclick="reloadPage()">Reload Page</button>
<button onclick="changeTitle()">Change Title</button>
</div>
<div class="event-log">
<h3>Event Log</h3>
<div id="log-output"></div>
<button onclick="clearLog()">Clear Log</button>
</div>
<!-- Dummy content to enable scrolling -->
<div class="dummy-content">
<h3>Scroll Area</h3>
<p>Scroll down to see scroll position update...</p>
<div style="height: 2000px; background: linear-gradient(#f0f0f0, #ffffff);"></div>
</div>
</div>
<script>
// DOM elements
const windowWidth = document.getElementById('window-width');
const windowHeight = document.getElementById('window-height');
const scrollX = document.getElementById('scroll-x');
const scrollY = document.getElementById('scroll-y');
const docTitle = document.getElementById('doc-title');
const docUrl = document.getElementById('doc-url');
const onlineStatus = document.getElementById('online-status');
const lastOnline = document.getElementById('last-online');
const logOutput = document.getElementById('log-output');
// Initial display
updateWindowInfo();
updateScrollInfo();
updateDocumentInfo();
updateOnlineStatus();
// Event listeners
window.addEventListener('resize', updateWindowInfo);
window.addEventListener('scroll', updateScrollInfo);
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
document.addEventListener('visibilitychange', () => {
logEvent(`Page ${document.hidden ? 'hidden' : 'visible'}`);
});
// Update functions
function updateWindowInfo() {
windowWidth.textContent = window.innerWidth;
windowHeight.textContent = window.innerHeight;
logEvent(`Window resized: ${window.innerWidth}x${window.innerHeight}`);
}
function updateScrollInfo() {
scrollX.textContent = window.scrollX || window.pageXOffset;
scrollY.textContent = window.scrollY || window.pageYOffset;
}
function updateDocumentInfo() {
docTitle.textContent = document.title;
docUrl.textContent = document.URL;
}
function updateOnlineStatus() {
const isOnline = navigator.onLine;
onlineStatus.textContent = isOnline ? '🟢 Online' : '🔴 Offline';
onlineStatus.style.color = isOnline ? 'green' : 'red';
if (isOnline) {
const now = new Date().toLocaleTimeString();
lastOnline.textContent = now;
logEvent('🟢 Back online');
} else {
logEvent('🔴 Went offline');
}
}
// Control functions
function scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
logEvent('Scrolled to top');
}
function scrollToBottom() {
window.scrollTo({
top: document.documentElement.scrollHeight,
behavior: 'smooth'
});
logEvent('Scrolled to bottom');
}
function openPopup() {
const popup = window.open(
'',
'popupWindow',
'width=400,height=300,left=100,top=100'
);
if (popup) {
popup.document.write(`
<html>
<head><title>Popup</title></head>
<body style="padding: 20px; font-family: Arial;">
<h2>Hello from Popup!</h2>
<p>This is a popup window.</p>
<button onclick="window.close()">Close</button>
</body>
</html>
`);
logEvent('Opened popup window');
}
}
function reloadPage() {
if (confirm('Are you sure you want to reload the page?')) {
window.location.reload();
}
}
function changeTitle() {
const newTitle = prompt('Enter new page title:', document.title);
if (newTitle) {
document.title = newTitle;
updateDocumentInfo();
logEvent(`Changed title to: "${newTitle}"`);
}
}
function logEvent(message) {
const time = new Date().toLocaleTimeString();
const logEntry = document.createElement('div');
logEntry.textContent = `[${time}] ${message}`;
logEntry.style.padding = '5px 0';
logEntry.style.borderBottom = '1px solid #eee';
logOutput.prepend(logEntry); // Add to top
// Limit log entries
if (logOutput.children.length > 20) {
logOutput.lastChild.remove();
}
}
function clearLog() {
logOutput.innerHTML = '';
logEvent('Log cleared');
}
// Initial log entry
logEvent('Page loaded');
</script>
<style>
.layout-manager {
max-width: 1000px;
margin: 20px auto;
padding: 20px;
font-family: Arial, sans-serif;
}
.info-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin: 20px 0;
}
.info-card {
padding: 15px;
border: 1px solid #ddd;
border-radius: 8px;
background: #f9f9f9;
}
.info-card h3 {
margin-top: 0;
color: #333;
border-bottom: 2px solid #4CAF50;
padding-bottom: 5px;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin: 20px 0;
padding: 20px;
background: #f0f0f0;
border-radius: 8px;
}
.controls button {
padding: 10px 15px;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background 0.3s;
}
.controls button:hover {
background: #45a049;
}
.event-log {
margin: 20px 0;
padding: 15px;
border: 1px solid #ddd;
border-radius: 8px;
background: #f9f9f9;
max-height: 300px;
overflow-y: auto;
}
#log-output {
font-family: monospace;
font-size: 0.9em;
margin: 10px 0;
padding: 10px;
background: white;
border-radius: 4px;
min-height: 100px;
max-height: 200px;
overflow-y: auto;
}
.dummy-content {
margin-top: 30px;
padding: 20px;
border: 1px dashed #ccc;
border-radius: 8px;
}
</style>
Browser API Tester
html
<div class="api-tester">
<h2>Browser API Tester</h2>
<div class="api-section">
<h3>📝 Clipboard API</h3>
<textarea id="clipboard-text" placeholder="Type text to copy..."></textarea>
<div class="button-group">
<button onclick="copyToClipboard()">Copy Text</button>
<button onclick="pasteFromClipboard()">Paste Text</button>
</div>
<div id="clipboard-result"></div>
</div>
<div class="api-section">
<h3>📍 Geolocation API</h3>
<div class="button-group">
<button onclick="getLocation()">Get Location</button>
<button onclick="watchLocation()">Watch Location</button>
<button onclick="stopWatchingLocation()">Stop Watching</button>
</div>
<div id="location-result"></div>
<div id="map" style="height: 200px; margin-top: 10px; display: none;"></div>
</div>
<div class="api-section">
<h3>📷 Media Devices</h3>
<div class="button-group">
<button onclick="accessCamera()">Access Camera</button>
<button onclick="stopCamera()">Stop Camera</button>
</div>
<video id="camera-feed" autoplay style="width: 100%; max-width: 400px; display: none;"></video>
<canvas id="photo-canvas" style="display: none;"></canvas>
<button onclick="takePhoto()" style="display: none;">Take Photo</button>
<div id="photos-container"></div>
</div>
<div class="api-section">
<h3>💾 Storage Info</h3>
<div id="storage-info">
<p>LocalStorage used: <span id="localstorage-size">0</span> KB</p>
<p>SessionStorage used: <span id="sessionstorage-size">0</span> KB</p>
<p>Cookies: <span id="cookies-info">0</span></p>
</div>
<button onclick="updateStorageInfo()">Update Storage Info</button>
<button onclick="clearAllStorage()">Clear All Storage</button>
</div>
<div class="api-section">
<h3>📊 Performance API</h3>
<div id="performance-info">
<p>Page loaded in: <span id="page-load-time">-</span> ms</p>
<p>Memory: <span id="memory-usage">-</span></p>
</div>
<button onclick="measurePerformance()">Measure Performance</button>
</div>
</div>
<script>
// Clipboard API
async function copyToClipboard() {
const text = document.getElementById('clipboard-text').value;
try {
await navigator.clipboard.writeText(text);
showResult('clipboard-result', 'Text copied to clipboard!', 'success');
} catch (err) {
showResult('clipboard-result', 'Failed to copy: ' + err.message, 'error');
}
}
async function pasteFromClipboard() {
try {
const text = await navigator.clipboard.readText();
document.getElementById('clipboard-text').value = text;
showResult('clipboard-result', 'ext pasted from clipboard!', 'success');
} catch (err) {
showResult('clipboard-result', ' Failed to paste: ' + err.message, 'error');
}
}
// Geolocation API
let watchId = null;
function getLocation() {
if (!navigator.geolocation) {
showResult('location-result', 'Geolocation not supported', 'error');
return;
}
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
showResult('location-result',
`Location found:<br>Latitude: ${latitude.toFixed(6)}<br>Longitude: ${longitude.toFixed(6)}<br>Accuracy: ${position.coords.accuracy}m`,
'success'
);
showMap(latitude, longitude);
},
(error) => {
showResult('location-result', ` Error: ${error.message}`, 'error');
},
{ enableHighAccuracy: true, timeout: 10000 }
);
}
function watchLocation() {
if (watchId) {
showResult('location-result', 'Already watching location', 'warning');
return;
}
watchId = navigator
}
Comments (0)
No comments yet. Be the first to comment!