From 4b5b3e16c8260a429db07dd54420ae40794b96c2 Mon Sep 17 00:00:00 2001 From: Chris Mills Date: Tue, 27 Aug 2024 15:51:27 +0100 Subject: [PATCH] Add visual viewport scrollend event ref page (#34427) * Add visual viewport scrollend event ref page * correct scrollend linking errors * Fix for wbamberg review comment * Added useful example and better use case explanations * fixes for wbamberg 2nd round review comments * Update code explanation as the demo has changed * Update files/en-us/web/api/visual_viewport_api/index.md Co-authored-by: wbamberg * Last few fixes for wbamberg comments --------- Co-authored-by: wbamberg --- .../web/api/visual_viewport_api/index.md | 108 ++++++++++++------ files/en-us/web/api/visualviewport/index.md | 3 + .../api/visualviewport/resize_event/index.md | 18 +-- .../api/visualviewport/scroll_event/index.md | 18 +-- .../visualviewport/scrollend_event/index.md | 37 ++++++ 5 files changed, 120 insertions(+), 64 deletions(-) create mode 100644 files/en-us/web/api/visualviewport/scrollend_event/index.md diff --git a/files/en-us/web/api/visual_viewport_api/index.md b/files/en-us/web/api/visual_viewport_api/index.md index bfbcfdde8b06c16..e3f17687b7aaaf0 100644 --- a/files/en-us/web/api/visual_viewport_api/index.md +++ b/files/en-us/web/api/visual_viewport_api/index.md @@ -16,14 +16,16 @@ The **Visual Viewport API** provides an explicit mechanism for querying and modi The mobile web contains two viewports, the layout viewport and the visual viewport. The layout viewport covers all the elements on a page and the visual viewport is what is actually visible on the screen. When the user pinch-zooms into the page, the visual viewport shrinks but the layout viewport is unchanged. User-interface features like the on-screen keyboard (OSK) can shrink the visual viewport without affecting the layout viewport. -What happens when a web page element needs to be visible on screen regardless of the visible portion of a web page? For example, what if you need a set of image controls to remain on screen regardless of the pinch zoom level of the device? Current browsers vary in how they handle this. The visual viewport lets web developers solve this by positioning elements relative to what's shown on screen. +What happens when a web page element needs to be visible on screen regardless of the visible portion of a web page? For example, what if you need a set of image controls to remain on screen regardless of the pinch-zoom level of the device? Current browsers vary in how they handle this. The visual viewport lets web developers solve this by positioning elements relative to what's shown on-screen. -To access a window's visual viewport, you can obtain a {{domxref("VisualViewport")}} object from the {{domxref("window.visualViewport")}} property. The object includes a set of properties describing the viewport. It also adds two events, `onresize` and `onscroll`, that fire whenever the visual viewport changes. These events allow you to position elements relative to the visual viewport that would normally be anchored to the layout viewport. +To access a window's visual viewport, you can obtain a {{domxref("VisualViewport")}} object from the {{domxref("window.visualViewport")}} property. The object includes a set of properties describing the viewport. It also adds three events, {{domxref("VisualViewport/resize_event", "resize")}}, {{domxref("VisualViewport/scroll_event", "scroll")}}, and {{domxref("VisualViewport/scrollend_event", "scrollend")}}, which fire when the visual viewport is resized, scrolls, and finishes a scrolling action, respectively. + +The first two events allow you to position elements relative to the visual viewport as it is scrolled or zoomed, which would normally be anchored to the layout viewport. The `scrollend` event allows you to update an element when a scrolling action is completed. For example, you can use these events to keep an element fixed to the visual viewport as it is pinch-zoomed and scrolled, and update it when scrolling ends. ## Interfaces - {{DOMxRef("VisualViewport")}} - - : Represents the visual viewport for a given window. A window's `VisualViewport` object provides information about the viewport's position and size, and receives the {{domxref("VisualViewport.resize_event", "resize")}} and {{domxref("VisualViewport.scroll_event", "scroll")}} events you can monitor to know when changes occur to the window's viewport. + - : Represents the visual viewport for a given window. A window's `VisualViewport` object provides information about the viewport's position and size, and receives the {{domxref("VisualViewport.resize_event", "resize")}}, {{domxref("VisualViewport.scroll_event", "scroll")}} and {{domxref("VisualViewport.scrollend_event", "scrollend")}} events. ### Extensions to other interfaces @@ -32,42 +34,84 @@ To access a window's visual viewport, you can obtain a {{domxref("VisualViewport ## Examples -The code below is based on [the sample in the specification](https://github.com/WICG/visual-viewport/blob/gh-pages/examples/fixed-to-viewport.html), though it adds a few things that make it function better. It shows a function called `viewportHandler()`. When called it queries the `offsetLeft` and `height` properties for values it uses in a CSS `translate()` method. You invoke this function by passing it to _both_ event calls. +Our [Visual Viewport API](https://mdn.github.io/dom-examples/visual-viewport-api/) example provides a basic demonstration of how the different visual viewport features work, including the three event types. Load the page in supporting desktop and mobile browsers and try scrolling around the page and pinch-zooming. On `resize` and `scroll`, the information box is repositioned to keep the same position relative to the visual viewport, and the viewport and scroll information it shows is updated. Also, on `resize` and `scroll` we change the box color to indicate something is happening, changing it back on `scrollend`. + +You'll find that on desktop browsers the {{domxref("Window.scrollX")}} and {{domxref("Window.scrollY")}} values are updated as the window is scrolled — the visual viewport position does not change. On mobile browsers however, the {{domxref("VisualViewport.offsetLeft")}} and {{domxref("VisualViewport.offsetTop")}} values are generally updated — it is usually the visual viewport that changes rather than the window position. + +The example HTML can be seen below. The information box is represented by a {{htmlelement("div")}} with an `id` of `output`. + +```html +

+ Try scrolling around and pinch-zooming to see how the reported values change. +

+
+

+
+

+
+``` + +We won't explain the example's CSS for the sake of brevity — it is not important for understanding the demo. You can check it out at the example link above. + +In the JavaScript, we start by getting references to the information box we'll be updating as the page is zoomed and scrolled, as well as the two paragraphs contained within it. The first one will contain reported {{domxref("VisualViewport.offsetLeft")}} and {{domxref("VisualViewport.offsetTop")}} values, while the second one will contain reported {{domxref("Window.scrollX")}} and {{domxref("Window.scrollY")}} values. + +```js +const output = document.getElementById("output"); +const visualInfo = document.getElementById("visual-info"); +const windowInfo = document.getElementById("window-info"); +``` + +Next, we define the two key functions we'll run when the events fire: -One thing that may not be clear in this example is the use of the `pendingUpdate` flag and the call to `requestAnimationFrame()`. The `pendingUpdate` flag serves to prevent multiple invocations of the transform that can occur when `onresize` and `onscroll` fire at the same time. Using `requestAnimationFrame()` ensures that the transform occurs before the next render. +- `scrollUpdater()` will fire on `resize` and `scroll`: this function updates the position of the information box relative to the visual viewport by querying the {{domxref("VisualViewport.offsetTop")}} and {{domxref("VisualViewport.offsetLeft")}} properties and using their values to update the values of the relevant {{glossary("inset properties")}}. We also change the information box's background color to indicate that something is happening, and run the `updateText()` function to update the values shown in the box. +- The `scrollEndUpdater()` function will fire on `scrollend`: this returns the information box to its original color and runs the `updateText()` function to make sure the latest values are shown on `scrollend`. ```js -let pendingUpdate = false; - -function viewportHandler(event) { - if (pendingUpdate) return; - pendingUpdate = true; - - requestAnimationFrame(() => { - pendingUpdate = false; - const layoutViewport = document.getElementById("layoutViewport"); - - // Since the bar is position: fixed we need to offset it by the - // visual viewport's offset from the layout viewport origin. - const viewport = event.target; - const offsetLeft = viewport.offsetLeft; - const offsetTop = - viewport.height - - layoutViewport.getBoundingClientRect().height + - viewport.offsetTop; - - // You could also do this by setting style.left and style.top if you - // use width: 100% instead. - bottomBar.style.transform = `translate(${offsetLeft}px, ${offsetTop}px) scale(${ - 1 / viewport.scale - })`; - }); +const scrollUpdater = () => { + output.style.top = `${visualViewport.offsetTop + 10}px`; + output.style.left = `${visualViewport.offsetLeft + 10}px`; + output.style.background = "yellow"; + updateText(); +}; + +const scrollendUpdater = () => { + output.style.background = "lime"; + updateText(); +}; +``` + +The `updateText()` function looks like so — it sets the {{domxref("HTMLElement.innerText")}} of the first paragraph to show the current `VisualViewport.offsetLeft` and `VisualViewport.offsetTop` values, and the `HTMLElement.innerText` of the second paragraph to show the current `Window.scrollX` and `Window.scrollY` values. After defining `updateText()`, we immediately invoke it so that the information box displays correctly on page load. + +```js +function updateText() { + visualInfo.innerText = `Visual viewport left: ${visualViewport.offsetLeft.toFixed(2)} + top: ${visualViewport.offsetTop.toFixed(2)}`; + windowInfo.innerText = `Window scrollX: ${window.scrollX.toFixed(2)} + scrollY: ${window.scrollY.toFixed(2)}`; } -window.visualViewport.addEventListener("scroll", viewportHandler); -window.visualViewport.addEventListener("resize", viewportHandler); +updateText(); ``` +> [!NOTE] +> We truncate all values to two decimal places using the {{jsxref("Number.toFixed()")}} method because some browsers display them as a subpixel value, potentially with a large number of decimal places. + +Now we set event handler properties on both the visual viewport and the {{domxref("Window")}} object to run the key functions at the appropriate times on both mobile and desktop: + +- We set the handlers on `window` so that the information box position and contents will update on conventional window scrolling operations, for example when you scroll the page on a desktop browser. +- We set the handlers on `visualViewport` so that the information box position and contents will update on visual viewport scrolling/zooming operations, for example when you scroll and pinch-zoom the page on a mobile browser. + +```js +visualViewport.onresize = scrollUpdater; +visualViewport.onscroll = scrollUpdater; +visualViewport.onscrollend = scrollendUpdater; +window.onresize = scrollUpdater; +window.onscroll = scrollUpdater; +window.onscrollend = scrollendUpdater; +``` + +`scrollUpdater()` will fire on `resize` and `scroll`, while `scrollEndUpdater()` will fire on `scrollend`. + ## Specifications {{Specifications}} diff --git a/files/en-us/web/api/visualviewport/index.md b/files/en-us/web/api/visualviewport/index.md index c434e41e2b8431d..e4c153c66fffdc9 100644 --- a/files/en-us/web/api/visualviewport/index.md +++ b/files/en-us/web/api/visualviewport/index.md @@ -49,6 +49,9 @@ Listen to these events using {{domxref("EventTarget.addEventListener", "addEvent - {{domxref("VisualViewport/scroll_event", "scroll")}} - : Fired when the visual viewport is scrolled. Also available via the `onscroll` property. +- {{domxref("VisualViewport/scrollend_event", "scrollend")}} + - : Fired when a scrolling operation on the visual viewport ends. + Also available via the `onscrollend` property. ## Examples diff --git a/files/en-us/web/api/visualviewport/resize_event/index.md b/files/en-us/web/api/visualviewport/resize_event/index.md index d158e75636a86a4..c791c1091325863 100644 --- a/files/en-us/web/api/visualviewport/resize_event/index.md +++ b/files/en-us/web/api/visualviewport/resize_event/index.md @@ -8,7 +8,7 @@ browser-compat: api.VisualViewport.resize_event {{APIRef("Visual Viewport")}} -The **`resize`** event of the {{domxref("VisualViewport")}} interface is fired when the visual viewport is resized. +The **`resize`** event of the {{domxref("VisualViewport")}} interface is fired when the visual viewport is resized. This allows you to position elements relative to the visual viewport as it is zoomed, which would normally be anchored to the layout viewport. ## Syntax @@ -26,21 +26,7 @@ A generic {{domxref("Event")}}. ## Examples -You can use the `resize` event in an {{domxref("EventTarget.addEventListener", "addEventListener()")}} method: - -```js -visualViewport.addEventListener("resize", () => { - // … -}); -``` - -Or use the `onresize` event handler property: - -```js -visualViewport.onresize = () => { - // … -}; -``` +See the [Visual Viewport API](/en-US/docs/Web/API/Visual_Viewport_API#examples) landing page for a usage demo. ## Specifications diff --git a/files/en-us/web/api/visualviewport/scroll_event/index.md b/files/en-us/web/api/visualviewport/scroll_event/index.md index 223fdaf3364c93e..08ad0204e0e91a9 100644 --- a/files/en-us/web/api/visualviewport/scroll_event/index.md +++ b/files/en-us/web/api/visualviewport/scroll_event/index.md @@ -8,7 +8,7 @@ browser-compat: api.VisualViewport.scroll_event {{APIRef("Visual Viewport")}} -The **`scroll`** event of the {{domxref("VisualViewport")}} interface is fired when the visual viewport is scrolled. +The **`scroll`** event of the {{domxref("VisualViewport")}} interface is fired when the visual viewport is scrolled. This allows you to position elements relative to the visual viewport as it is scrolled, which would normally be anchored to the layout viewport. ## Syntax @@ -26,21 +26,7 @@ A generic {{domxref("Event")}}. ## Examples -You can use the `scroll` event in an {{domxref("EventTarget.addEventListener", "addEventListener()")}} method: - -```js -visualViewport.addEventListener("scroll", () => { - // … -}); -``` - -Or use the `onscroll` event handler property: - -```js -visualViewport.onscroll = () => { - // … -}; -``` +See the [Visual Viewport API](/en-US/docs/Web/API/Visual_Viewport_API#examples) landing page for a usage demo. ## Specifications diff --git a/files/en-us/web/api/visualviewport/scrollend_event/index.md b/files/en-us/web/api/visualviewport/scrollend_event/index.md new file mode 100644 index 000000000000000..d70e89503642cfd --- /dev/null +++ b/files/en-us/web/api/visualviewport/scrollend_event/index.md @@ -0,0 +1,37 @@ +--- +title: "VisualViewport: scrollend event" +short-title: scrollend +slug: Web/API/VisualViewport/scrollend_event +page-type: web-api-event +browser-compat: api.VisualViewport.scrollend_event +--- + +{{APIRef("Visual Viewport")}} + +The **`scrollend`** event of the {{domxref("VisualViewport")}} interface is fired when a scrolling operation on the visual viewport ends. This allows you to update an element when a scrolling action is completed. For example, you could use the {{domxref("VisualViewport/resize_event", "resize")}} and {{domxref("VisualViewport/scroll_event", "scroll")}} events to keep an element fixed to the visual viewport as it is pinch-zoomed and scrolled, and update it with new content when scrolling ends using `scrollend`. + +## Syntax + +Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. + +```js +addEventListener("scrollend", (event) => {}); + +onscrollend = (event) => {}; +``` + +## Event type + +A generic {{domxref("Event")}}. + +## Examples + +See the [Visual Viewport API](/en-US/docs/Web/API/Visual_Viewport_API#examples) landing page for a usage demo. + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}}