Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
⚡ Days 15–22 – Advanced और Async JavaScript  ·  दिन 22

दिन 22: काम के Browser APIs

⏱ 95 min📶 Intermediate → Pro🎯 100% self-study
दिन 22 / 30

✅ आज आप सीखेंगे

  • Share होने वाले filters के लिए URL और URLSearchParams
  • History API: pushState, popstate
  • IntersectionObserver: lazy loading, infinite scroll, reveal animations
  • Clipboard, Web Share और WhatsApp deep links
  • Geolocation और permissions – ज़िम्मेदारी से

🏢 असली दुनिया में

दुकान मालिक पूछते हैं: “जब मैं customer को ₹700 से कम milk sweets का link भेजूँ, तो वह filter पहले से लगा खुले।” “क्या customers एक tap में coupon copy और product WhatsApp पर share कर सकते हैं?” “क्या पता चले customer दुकान से कितना दूर है?” यह सब browser में built-in है – कोई libraries नहीं चाहिए।

URL और URLSearchParams

JavaScript
const link = new URL('https://sharmasweets.in/menu?category=milk&max=700&sort=price#list');
console.log(link.hostname, link.pathname, link.hash);
console.log(link.searchParams.get('category'), Number(link.searchParams.get('max')));
console.log(link.searchParams.has('veg'));

link.searchParams.set('max', 900);          // update
link.searchParams.append('tag', 'sugar-free');
link.searchParams.delete('sort');
console.log(link.toString());

const p = new URLSearchParams({ q: 'kaju katli', city: 'Jaipur' });
console.log(p.toString());                  // spaces and special characters encoded safely
sharmasweets.in /menu #list milk 700 false https://sharmasweets.in/menu?category=milk&max=900&tag=sugar-free#list q=kaju+katli&city=Jaipur

History API से share होने वाले filters

HTML + JavaScript
<label>Category <select id="cat"><option value="">All</option><option value="milk">Milk</option><option value="dry">Dry</option></select></label>
<label>Max ₹ <input id="max" type="number" step="100" value="1000" style="width:90px"></label>
<p>Address bar would show: <code id="addr"></code></p>
<ul id="list"></ul>

<script>
const products = [
  { name: 'Kaju Katli', category: 'dry', price: 900 }, { name: 'Ghewar', category: 'milk', price: 650 },
  { name: 'Rasmalai', category: 'milk', price: 700 }, { name: 'Ladoo', category: 'dry', price: 500 },
];
const cat = document.querySelector('#cat'), max = document.querySelector('#max');

function render() {
  const list = products.filter(p => (!cat.value || p.category === cat.value) && p.price <= Number(max.value));
  document.querySelector('#list').innerHTML = list.map(p => `<li>${p.name} – ₹${p.price}</li>`).join('') || '<li>None</li>';
}
function updateUrl() {
  const params = new URLSearchParams();
  if (cat.value) params.set('category', cat.value);
  if (max.value !== '1000') params.set('max', max.value);
  const url = location.pathname + (params.toString() ? '?' + params : '');
  try { history.pushState({ category: cat.value, max: max.value }, '', url); } catch (e) { /* sandboxed preview */ }
  document.querySelector('#addr').textContent = '/menu' + (params.toString() ? '?' + params : '');
}
// read filters from the URL on load (works on a real page)
const start = new URLSearchParams(location.search);
if (start.get('category')) cat.value = start.get('category');
if (start.get('max')) max.value = start.get('max');

[cat, max].forEach(el => el.addEventListener('input', () => { updateUrl(); render(); }));
window.addEventListener('popstate', (e) => {          // Back / Forward buttons
  cat.value = e.state?.category ?? ''; max.value = e.state?.max ?? '1000'; render();
});
updateUrl(); render();
</script>
▶  Change the filters – the URL updates so the exact view can be shared or bookmarked

IntersectionObserver: चीज़ें दिखने पर प्रतिक्रिया

HTML + JavaScript
<style>
.reveal { padding: 18px; margin: 8px 0; background: #fef3c7; border-radius: 10px; opacity: 0; transform: translateY(16px); transition: .5s; }
.reveal.show { opacity: 1; transform: none; }
</style>

<p>Scroll inside this box ↓</p>
<div id="feed" style="height:260px;overflow:auto;border:1px solid #e5e7eb;border-radius:10px;padding:10px"></div>

<script>
const feed = document.querySelector('#feed');
let page = 0;
const names = ['Kaju Katli', 'Ghewar', 'Rasmalai', 'Ladoo', 'Kalakand', 'Soan Papdi', 'Peda', 'Jalebi'];

const sentinel = document.createElement('p');      // invisible marker at the bottom
sentinel.textContent = 'Loading more…';

function addPage() {
  page++;
  for (let i = 0; i < 4; i++) {
    const card = document.createElement('div');
    card.className = 'reveal';
    card.textContent = `#${(page - 1) * 4 + i + 1} ${names[((page - 1) * 4 + i) % names.length]}`;
    feed.insertBefore(card, sentinel);
    revealObserver.observe(card);
  }
  if (page >= 5) { sentinel.textContent = 'That’s all 🍬'; moreObserver.disconnect(); }
}

// 1. Reveal animation when a card enters the box
const revealObserver = new IntersectionObserver((entries) => {
  entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('show'); revealObserver.unobserve(e.target); } });
}, { root: feed, threshold: 0.3 });

// 2. Infinite scroll: load the next page when the sentinel appears
const moreObserver = new IntersectionObserver((entries) => {
  if (entries[0].isIntersecting) addPage();
}, { root: feed, rootMargin: '80px' });

feed.append(sentinel);
moreObserver.observe(sentinel);
</script>
▶  Cards fade in and new pages load automatically – no scroll events
उपयोगकैसे
Images lazy-loadimg[data-src] observe करें; दिखने पर src लगाएँ (या बस loading="lazy")
Infinite scrollList के अंत में sentinel observe करके अगला page fetch
Scroll reveal animationsViewport में आने पर class जोड़ें
Analytics “seen” eventsBanner 1 s तक 50% दिखे तो viewed गिनें
Videos रोकनाScreen से बाहर जाने पर pause
💡 scroll event क्यों नहीं?

scroll हर सेकंड दर्जनों बार चलता है और positions मापने से layout गणना होती है – सस्ते phones पर झटके। IntersectionObserver browser कुशलता से गिनता है और तभी बुलाता है जब दिखना सच में बदले।

Clipboard, Web Share और WhatsApp links

HTML + JavaScript
<p>Coupon: <code id="code">SWEET10</code> <button id="copy">Copy</button></p>
<p><button id="share">Share this product</button>
<a id="wa" target="_blank" rel="noopener">Order on WhatsApp</a></p>
<p id="msg" role="status"></p>

<script>
const msg = document.querySelector('#msg');

document.querySelector('#copy').addEventListener('click', async () => {
  const code = document.querySelector('#code').textContent;
  try {
    await navigator.clipboard.writeText(code);          // needs HTTPS and a user click
    msg.textContent = 'Copied ✅';
  } catch (err) {
    msg.textContent = 'Copy blocked here – select and copy manually: ' + code;
  }
});

document.querySelector('#share').addEventListener('click', async () => {
  const data = { title: 'Kaju Katli – Sharma Sweets', text: 'Fresh kaju katli ₹900/kg 🍬', url: 'https://sharmasweets.in/menu#kaju' };
  if (navigator.share) {
    try { await navigator.share(data); msg.textContent = 'Shared!'; }
    catch (err) { msg.textContent = 'Share cancelled'; }
  } else {
    msg.textContent = 'Web Share is not available on this device – use the WhatsApp link.';
  }
});

const text = 'Namaste! I want to order 1 kg Kaju Katli for delivery tomorrow.';
document.querySelector('#wa').href = 'https://wa.me/919829012345?text=' + encodeURIComponent(text);
</script>
▶  Copy to clipboard, native share sheet on phones and a pre-filled WhatsApp order
🧠 encodeURIComponent

URLs के अंदर spaces, &, ? और Hindi text encode करने होते हैं। encodeURIComponent “1 kg Kaju & Ghewar” को सुरक्षित string बनाता है – भूलने पर WhatsApp message पहले & पर टूट जाता है।

Geolocation: दुकान से दूरी

HTML + JavaScript
<button id="locate">How far am I from the shop?</button>
<p id="dist" role="status"></p>

<script>
const SHOP = { lat: 26.9196, lon: 75.8235 };        // Johari Bazaar, Jaipur

function km(a, b) {                                  // Haversine formula
  const R = 6371, rad = d => d * Math.PI / 180;
  const dLat = rad(b.lat - a.lat), dLon = rad(b.lon - a.lon);
  const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
  return 2 * R * Math.asin(Math.sqrt(h));
}

document.querySelector('#locate').addEventListener('click', () => {
  const out = document.querySelector('#dist');
  if (!('geolocation' in navigator)) { out.textContent = 'Location not supported'; return; }
  out.textContent = 'Asking for permission…';
  navigator.geolocation.getCurrentPosition(
    pos => {
      const d = km(SHOP, { lat: pos.coords.latitude, lon: pos.coords.longitude });
      out.textContent = `You are about ${d.toFixed(1)} km away. ${d <= 15 ? 'We deliver to you 🛵' : 'Courier for dry sweets 📦'}`;
    },
    err => { out.textContent = 'Location unavailable (' + err.message + '). Enter your PIN code instead.'; },
    { enableHighAccuracy: false, timeout: 8000, maximumAge: 600000 }
  );
});
</script>
▶  Uses permission – in this sandboxed preview it falls back to the error path
APIचाहिएअच्छा तरीक़ा
GeolocationHTTPS + अनुमतिClick के बाद ही पूछें, कारण बताएँ, PIN-code विकल्प दें
Clipboard writeHTTPS + user gesture“Copied” पुष्टि दिखाएँ
Web ShareHTTPS, ज़्यादातर mobileFeature-detect करके fallback link दें
NotificationsअनुमतिUser के चुनने पर ही पूछें (जैसे “ghewar आए तो बताओ”)
Page Visibilityकुछ नहींdocument.hidden पर timers/polling रोकें

🏅 आज के Job Skills

✔ URL parameters पढ़ना-लिखना और filters address bar में रखना✔ Lazy loading, infinite scroll और reveals के लिए IntersectionObserver✔ Copy, share और WhatsApp features✔ Fallbacks के साथ geolocation और permissions ज़िम्मेदारी से

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: Cart array [{name, qty}] से WhatsApp order link बनाएँ जिसमें हर item नई line पर हो।
Solution देखें
JavaScript
const cart = [{ name: 'Kaju Katli', qty: 2 }, { name: 'Ghewar', qty: 1 }, { name: 'Ladoo & Peda box', qty: 1 }];
const lines = ['Namaste Sharma Sweets 🙏', 'My order:', ...cart.map(i => `• ${i.name} × ${i.qty}`), 'Please confirm.'];
const url = 'https://wa.me/919829012345?text=' + encodeURIComponent(lines.join('\n'));
console.log(url);
https://wa.me/919829012345?text=Namaste%20Sharma%20Sweets%20%F0%9F%99%8F%0AMy%20order%3A%0A%E2%80%A2%20Kaju%20Katli%20%C3%97%202%0A%E2%80%A2%20Ghewar%20%C3%97%201%0A%E2%80%A2%20Ladoo%20%26%20Peda%20box%20%C3%97%201%0APlease%20confirm.
Task 2: URL से ?lang=hi पढ़कर heading को English और Hindi में बदलें।
Task 3: Tab छिपने पर document.visibilityState से countdown timer रोकें।

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. new URLSearchParams('a=1&b=2').get('b') है…
हमेशा strings।
2. history.pushState…
Back के लिए popstate सुनें।
3. Infinite scroll के लिए सबसे अच्छा?
कुशल visibility जाँच।
4. wa.me link का text होना चाहिए…
सुरक्षित characters।
5. Location permission कब माँगें?
संदर्भ भरोसा बनाता है।

Interview corner

💼 Interview Corner

Infinite scroll कैसे लागू करेंगे?

पहला page render करें, list के बाद sentinel element रखकर उसे IntersectionObserver से observe करें (prefetch के लिए rootMargin)। Intersect होने पर अगला page fetch करें (duplicate requests से बचते हुए), items जोड़ें, और अंत में observe बंद करें। Back navigation के लिए URLs/state रखें और बहुत लंबी lists के लिए virtualisation सोचें।

Filters URL में क्यों रखें?

URLs share, bookmark हो सकते हैं, Back/Forward से चलते हैं, refresh में बचते हैं और SEO व analytics में मदद करते हैं। URLSearchParams + history.pushState/replaceState बिना reload UI state और URL को sync रखते हैं।

सारांश

  • URL/URLSearchParams query strings सुरक्षित parse और build करते हैं।
  • pushState + popstate बिना reload filters share-योग्य रखते हैं।
  • Lazy load, infinite scroll और reveals के लिए IntersectionObserver।
  • Clipboard, Share, WhatsApp links और geolocation – HTTPS, अनुमति और fallbacks के साथ।
➡️ आगे

Day 23: regular expressions – mobile numbers, PIN codes, GSTIN, e-mail और passwords सही से validate करें।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

कुछ demos “blocked here” क्यों बोले?
Lesson previews सुरक्षा के लिए sandboxed frame में चलते हैं, जहाँ clipboard, location और history बदलाव सीमित हैं। वही code सामान्य HTTPS page पर चलता है।
क्या geolocation से user का पता मिल सकता है?
Geolocation सिर्फ़ coordinates देता है। पता बनाने के लिए geocoding service (जैसे Google Maps API) चाहिए – और साफ़ सहमति।
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 23: असली Validation के लिए Regular Expressions आपकी प्रगति: 22 / 30 (73%) · Lesson 23 / 30 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें