JS Browser APIs

Foundations · Prereqs: F-JS-002
--- theme: seriph title: "JS Browser APIs" info: "localStorage, setTimeout, geolocation, clipboard, URLSearchParams" --- # JS Browser APIs Your browser comes with built-in superpowers. Here are the ones you'll use most. --- layout: center --- # localStorage --- # Save Data Between Visits ```js // Save localStorage.setItem('username', 'Alice'); // Load const name = localStorage.getItem('username'); // Remove localStorage.removeItem('username'); ``` Data persists even after closing the tab. Stored as strings only. > AI tip: Ask AI to "add localStorage to save user preferences." It handles the save/load pattern well. --- # Saving Objects and Arrays ```js // Save an array const tasks = ['Buy milk', 'Read chapter 3']; localStorage.setItem('tasks', JSON.stringify(tasks)); // Load it back const saved = JSON.parse(localStorage.getItem('tasks')); ``` Always use `JSON.stringify` to save and `JSON.parse` to load non-string data. --- # Your Turn: Dark Mode Toggle Create `js/dark-mode.js`. Add a button that toggles dark mode and remembers the choice: 1. Button click toggles a `dark` class on `<body>` 2. Save the preference to localStorage 3. On page load, check localStorage and apply the class --- layout: center --- # Timers --- # setTimeout and setInterval ```js // Run once after 2 seconds setTimeout(() => { alert('Time is up!'); }, 2000); // Run every 1 second const timer = setInterval(() => { console.log('tick'); }, 1000); // Stop the interval clearInterval(timer); ``` > AI tip: "Build a countdown timer that updates every second" is a great prompt. Check that AI uses `clearInterval` to stop it. --- # Common Timer Patterns | Pattern | Use case | |---|---| | `setTimeout(fn, 0)` | Run after current code finishes | | `setInterval(fn, 1000)` | Update a clock or countdown | | Debounce with `setTimeout` | Wait for user to stop typing before searching | --- layout: center --- # Geolocation --- # Get the User's Location ```js navigator.geolocation.getCurrentPosition( (position) => { const lat = position.coords.latitude; const lon = position.coords.longitude; console.log(`You are at ${lat}, ${lon}`); }, (error) => { console.log('Location denied or unavailable'); } ); ``` The browser asks the user for permission first. Always handle the error case. > AI tip: "Get user location and show weather for their city" combines geolocation + fetch in one prompt. --- layout: center --- # Clipboard API --- # Copy to Clipboard ```js const copyButton = document.querySelector('#copy-btn'); copyButton.addEventListener('click', async () => { const text = document.querySelector('#output').textContent; await navigator.clipboard.writeText(text); copyButton.textContent = 'Copied!'; }); ``` Users love "copy to clipboard" buttons. One of the easiest ways to make your app feel polished. --- layout: center --- # URL Parameters --- # Reading URL Parameters If the URL is `page.html?city=Boston&units=metric`: ```js const params = new URLSearchParams(window.location.search); const city = params.get('city'); // "Boston" const units = params.get('units'); // "metric" ``` Useful for sharing links with pre-filled data (search results, filtered views). --- # Key Takeaways 1. **localStorage**: save data between visits (preferences, state) 2. **setTimeout/setInterval**: delays and repeating actions 3. **Geolocation**: location-based features (weather, maps) 4. **Clipboard**: "copy to clipboard" buttons 5. **URLSearchParams**: read and share URL parameters These are tools, not topics to memorize. Know they exist, ask AI to help you use them. --- # References - [MDN: Web APIs](https://developer.mozilla.org/en-US/docs/Web/API) - [MDN: localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) - [MDN: Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API)

Topics Covered

  • localStorage (save data between visits)
  • setTimeout / setInterval (timers)
  • Geolocation API
  • Clipboard API (copy to clipboard)
  • URLSearchParams (reading URL parameters)

Content Slides Open fullscreen ↗