All Projects → ljbc1994 → BlazorIntersectionObserver

ljbc1994 / BlazorIntersectionObserver

Licence: MIT license
🔎 Intersection Observer API wrapper for Blazor applications

Programming Languages

C#
18002 projects
typescript
32286 projects
javascript
184084 projects - #8 most used programming language
HTML
75241 projects

Projects that are alternatives of or similar to BlazorIntersectionObserver

react-intersection-observer-api-example
Showcasing of the Intersection Observer API in React with createRef()
Stars: ✭ 13 (-62.86%)
Mutual labels:  intersectionobserver, intersectionobserver-api
intersection-observer-examples
Practical, real world examples of Intersection Observer
Stars: ✭ 14 (-60%)
Mutual labels:  intersectionobserver, intersectionobserver-api
svelte-inview
A Svelte action that monitors an element enters or leaves the viewport.🔥
Stars: ✭ 358 (+922.86%)
Mutual labels:  intersectionobserver, intersectionobserver-api
React Intersection Observer
React implementation of the Intersection Observer API to tell you when an element enters or leaves the viewport.
Stars: ✭ 2,689 (+7582.86%)
Mutual labels:  intersectionobserver, intersectionobserver-api
mbill blazor admin
基于Blazor + Ant Blazor搭建个人记账后台管系统,采用.NET 6搭建后台服务,采用uni-app搭建个人记账微信小程序,采用Xamarin搭建移动客户端App
Stars: ✭ 19 (-45.71%)
Mutual labels:  blazor
Blazor-CRUD-With-CloudFirestore
Single Page Application (SPA) using Blazor with the help of Google Cloud Firestore as Database provider
Stars: ✭ 34 (-2.86%)
Mutual labels:  blazor
BlazorSimpleSurvey
Blazor Simple Survey
Stars: ✭ 39 (+11.43%)
Mutual labels:  blazor
NodaTimePicker
A Date/Time picker component library for Blazor using NodaTime
Stars: ✭ 49 (+40%)
Mutual labels:  blazor
planningpoker4azure
Planning Poker 4 Azure
Stars: ✭ 49 (+40%)
Mutual labels:  blazor
FindRazorSourceFile
This is a set of NuGet packages that makes your Blazor apps display the source .razor file name that generated the HTML element under the mouse cursor when entering the Ctrl + Shift + F hotkeys.
Stars: ✭ 39 (+11.43%)
Mutual labels:  blazor
Blazor.BrowserExtension
A package for building Browser Extension with Blazor WebAssembly application.
Stars: ✭ 207 (+491.43%)
Mutual labels:  blazor
blazor-dom-confetti
Celebrate success with dom confetti on Blazor projects!
Stars: ✭ 16 (-54.29%)
Mutual labels:  blazor
toast ui.blazor calendar
Toast UI Calendar Wrapper For Blazor
Stars: ✭ 42 (+20%)
Mutual labels:  blazor
Fritz.HatCollection
A static website that displays a collection of Fritz's Hats
Stars: ✭ 21 (-40%)
Mutual labels:  blazor
RazorComponents.Markdown
Razor component for Markdown rendering.
Stars: ✭ 30 (-14.29%)
Mutual labels:  blazor
timewarp-templates
A distributed application template for dotnet. Utilizing Blazor, Web API, gRPC, Tye, YARP etc.
Stars: ✭ 37 (+5.71%)
Mutual labels:  blazor
ant-design-blazor
Ant Design for Blazor (WIP)
Stars: ✭ 23 (-34.29%)
Mutual labels:  blazor
stl-part-viewer
A lit-element web component that uses Three.js to display an STL model file.
Stars: ✭ 19 (-45.71%)
Mutual labels:  intersectionobserver
NObservable
MobX like observable state management library with Blazor support
Stars: ✭ 66 (+88.57%)
Mutual labels:  blazor
SPA-With-Blazor
Creating a Single Page Application with Razor pages in Blazor using Entity Framework Core database first approach.
Stars: ✭ 27 (-22.86%)
Mutual labels:  blazor

BlazorIntersectionObserver

Package Version NuGet Downloads License

A comprehensive wrapper around the Intersection Observer API, giving you all the goodness of observing intersections in a performant way.

This is a wrapper around the Intersection Observer API so that you can use it in Blazor for .NET 5. It has the same API structure with convenience methods and components for a better dev experience. It works with both Blazor WebAssembly and Blazor Server.

Get Started

1. Installation

Install BlazorIntersectionObserver through NuGet.

> dotnet add package BlazorIntersectionObserver

2. Register the service

Now you'll need to add the service to the service configuration.

WebAssembly (Program.cs)

using Ljbc1994.Blazor.IntersectionObserver;

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.Services.AddIntersectionObserver();
    }
}

OR

Server (Startup.cs)

using Ljbc1994.Blazor.IntersectionObserver;

public class Startup {
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddIntersectionObserver();
    }
}

3. Use it!

For the quickest setup, use the IntersectionObserve component. This provides an implicit context object which contains the observer entry! Easy!

Component setup

@using Ljbc1994.Blazor.IntersectionObserver.Components

<IntersectionObserve>
    <div @ref="context.Ref.Current">
        Hey... I'm @(context.IsIntersecting ? "in view": "out of view")
    </div>
</IntersectionObserve>

OR

Service setup

To directly use the service, you just need to inject it and observe the element(s).

@using Ljbc1994.Blazor.IntersectionObserver
@inject IIntersectionObserverService ObserverService

<img @ref="ImageElement" src="@(IsIntersecting ? "https://www.placecage.com/g/500/500" : "")"/>

@functions {
    public ElementReference ImageElement { get; set; }
    public bool IsIntersecting { get; set; }
    
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender) 
        {
            await SetupObserver();
        }
    }

    public async void SetupObserver()
    {
        await ObserverService.Observe(ImageElement, (entries) =>
        {
            var entry = entries.FirstOrDefault();
            IsIntersecting = entry.IsIntersecting;
            StateHasChanged();
        });
    }
}

Documentation and Usage

Options

You can pass through options to the ObserverService methods, these are the same as the Intersection Observer API options.

Example

var options = new IntersectionObserverOptions {
    Root = BodyRef, 
    Threshold = new List<double> { 0.25, 0.5, 1 },
    RootMargin = "10px 10px 10px 10px"
};

Service Methods

Observe

This a shorthand way of observing an element by providing:

  • The element you want to observe.
  • The callback to trigger on an intersection update.
  • The intersection observer options.

This returns an IntersectionObserver instance, allowing you to disconnect the observer or unobserve an element. Or if you wish, observe additional elements.

var observer = await ObserverService.Observe(ElementRef, (entries) => {
    IsIntersecting = entries.FirstOrDefault().IsIntersecting;
    StateHasChanged();
}, options);

Create

The Create method follows the same approach as the Intersection Observer API, you create the observer and then pass elements you wish to observe by calling the Observe method on the observer instance. To create the observer, provide the following:

  • The callback to trigger on an intersection update.
  • The intersection observer options.

This returns an IntersectionObserver instance, allowing you to Observe elements. This also provides the ability to disconnect or unobserve the element.

var observer = await ObserverService.Create((entries) => {
    IsIntersecting = entries.FirstOrDefault().IsIntersecting;
    StateHasChanged();
}, options);

await observer.Observe(FirstImage);
await observer.Unobserve(FirstImage);

IntersectionObserver Methods

Observe

To observe an element, provide the element reference to the IntersectionObserver instance by calling Observe.

observer.Observe(ElementReference);

Unobserve

To unobserve an element, provide the element reference to the IntersectionObserver instance by calling Unobserve.

observer.Unobserve(ElementReference);

Disconnect

To disconnect the observer, call Disconnect on the IntersectionObserver instance.

observer.Disconnect();

This will remove all the observed elements from the observer, i.e.

@using Ljbc1994.Blazor.IntersectionObserver
@implements IAsyncDisposable
@inject IIntersectionObserverService ObserverService

<div @ref="ImageRef"></div>

@functions {
    private IntersectionObserver Observer;
    @* Code... *@

    public async ValueTask DisconnectAll()
    {
        if (this.Observer != null)
        {
            await this.Observer.Disconnect();
        }
    }
}

Dispose

To remove the observer, call Dispose on the IntersectionObserver instance.

observer.Dispose();

This is a useful method to clean up observers when components are disposed of, i.e.

@using Ljbc1994.Blazor.IntersectionObserver
@implements IAsyncDisposable
@inject IIntersectionObserverService ObserverService

<div @ref="ImageRef"></div>

@functions {
    private IntersectionObserver Observer;
    @* Code... *@

    public async ValueTask DisposeAsync()
    {
        if (this.Observer != null)
        {
            await this.Observer.Dispose();
        }
    }
}

Component

<IntersectionObserve>

Rather than directly interfacing with the service, you can use this convenience component for quick and easy observing. You can access the observer entry through the implicit @context!

You need to make sure to provide the reference of the element you want to observe, this is done by passing the element reference to the context reference.

@* Injecting service... *@

<IntersectionObserve>
    <div @ref="context.Ref.Current">
        Hey... look I'm @(context.IsIntersecting ? "intersecting!": "not intersecting!")
    </div>
</IntersectionObserve>

@* Component code... *@
Props
  • OnChange (EventCallback<IntersectionObserverEntry>) - When the intersection observer has a entry update.
  • IsIntersecting (bool) - Whether the element is intersecting - used for two-way binding.
  • Options (IntersectionObserverOptions) - The options for the observer.
  • Once (bool) - Only observe once for an intersection, then the instance disposes of itself.

Context

The context is the IntersectionObserverContext object, with the following signature:

public class IntersectionObserverContext 
{
    public IntersectionObserverEntry Entry { get; set; }
    public ForwardReference Ref { get; set; } = new ForwardReference();
    public bool IsIntersecting => this.Entry?.IsIntersecting ?? false;
}

public class IntersectionObserverEntry
{
    public bool IsIntersecting { get; set; }

    public double IntersectionRatio { get; set; }

    public DOMRectReadOnly BoundingClientRect { get; set; }

    public DOMRectReadOnly RootBounds { get; set; }

    public bool IsVisible { get; set; }

    public double Time { get; set; }
}

Additional Information

Upgrading to 2.0.1+

In versions prior to 2.0.1, the IntersectionObserve component didn't require a reference to the node as it was wrapped in an element that was automatically observed. This was changed to ensure the consumer provides the reference to prevent any potential layout issues and make it explicit what element should be observed.

Therefore, before 2.0.1, if the consumer had an element with display: none; within the IntersectionObserve component, this would have worked. However, as we're now observing the element provided as opposed to a wrapped element, this will no longer work. To resolve this, you can wrap the observed element in a div and observe the container div instead of the observed element.

Feature Requests

There's so much that IntersectionObserver can do, so if you have any requests or you want better documentation and examples, feel free to make a pull request or create an issue!

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].