Detect Element Visibility with Intersection Observer v2
Prompt
Create a demo of Intersection Observer v2 that detects not only intersection but also actual visibility (e.g., element hidden by transparent overlay or CSS opacity). Show multiple cards with different states: fully visible, partially covered by a semi-transparent overlay, and faded with opacity. Use colored borders/indicators to show visibility state changes.
CODE PREVIEW
AIとの対話に追加する一言
プロンプトと一緒にコピーして、AIがより正確に意図を汲み取れるようにします
このコードをそのまま使いたいので、CDNリンクも含めた完全なHTMLファイルとして出力してください。
初心者なので、各行にコメントを追加して、何をしているか説明してください。
このコードをWordPressのテーマに組み込む方法も教えてください。
動作確認済みのコードをお願いします。エラーが出る場合の対処法も含めて。
Intersection Observer v2 は、オリジナルの API に trackVisibility と delay オプション、さらにエントリの isVisible プロパティを追加します。これにより、要素がビューポートに入ったか出たかだけでなく、実際にユーザーから見えているかどうか(CSS の opacity や透明オーバーレイなどで隠されていないか)も検出できます。
このデモでは、6枚のカードに異なる可視性シナリオを用意しています。「covered (隠れている)」と表示されたカードは上に半透明のオーバーレイ (::after 疑似要素) があり、「faded (薄くなっている)」のカードは opacity: 0.3 以下に設定されています。オブザーバーが交差と可視性の両方を追跡し、各カードのバッジとインジケーターの色が変化します。
注意: trackVisibility: true と正の delay (例: 100ms) が v2 機能には必須です。ブラウザサポートは現在 Chromium ベースのブラウザに限られます。
Prompt Overview
Intersection Observer v2 extends the original API with trackVisibility and delay options, along with the isVisible property on entries. This allows you to detect not only when an element enters or exits the viewport, but also whether it is actually visible to the user — not hidden by CSS opacity, transparent overlays, or other visual obstructions.
In this demo, we have six cards with different visibility scenarios. Cards labeled as 'covered' have a semi-transparent overlay on top (using ::after pseudo-element), and cards labeled as 'faded' use opacity: 0.3 or lower. The observer tracks both intersection and visibility, updating each card's badge and indicator color accordingly.
Note: trackVisibility: true and a positive delay (e.g., 100ms) are required for v2 features. Browser support is currently limited to Chromium-based browsers.
Was this prompt helpful?
Comments
Comments appear after moderation
この記事が役に立ったら投げ銭で応援
Apple Pay / Google Pay / カード (Visa/Mastercard/JCB/Amex) / Link / Alipay / WeChat Pay 対応 · Stripeで安全に決済
開発者が選ぶ最強ツール集
運営者が毎日使っているツール・ガジェット 6選