---
name: "IntersectionObserver.relativeToViewport"
mode: "api"
versionRequirements:
  - { name: "Base Library", version: "2.10.0" }
title: "relativeToViewport"
---

## IntersectionObserver.relativeToViewport

> [VERSION] Base Library >= 2.10.0

### Description

Specify the page viewport as one of the reference regions

### Parameters

`Params`

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `margins` | `Margins` | No | Used to expand (or shrink) the viewport’s bounds |

### Return Value

Type: `IntersectionObserver`

[IntersectionObserver instance](/en/miniapp/develop/miniapp/api/tyml/IntersectionObserver/IntersectionObserver)(supports chaining)

### Referenced Types

##### `type` Margins

| Property | Type | Description |
| --- | --- | --- |
| `left` | `number` | Left boundary |
| `right` | `number` | Right boundary |
| `top` | `number` | Top boundary |
| `bottom` | `number` | Bottom boundary |


### Examples

#### Observe relative to the viewport

```html
// index.tyml
<scroll-view scroll-y="{{true}}" class="container">
  <view class="placeholder">Scroll down</view>
  <view class="target">Target</view>
</scroll-view>
```

```js
// index.js
Page({
  onReady() {
    var observer = ty.createIntersectionObserver(this);
    observer
      .relativeToViewport({ bottom: 100 })
      .observe('.target', (res) => {
        if (res.intersectionRatio > 0) {
          console.log('Element entered viewport');
        } else {
          console.log('Element left viewport');
        }
      });
  },
});
```

```css
// index.tyss
.container {
  height: 100vh;
}
.placeholder {
  height: 1000rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}
.target {
  height: 200rpx;
  background-color: #e8f4ff;
  display: flex;
  align-items: center;
  justify-content: center;
}
```
