Live Chat Icon For mobile
Live Chat Icon

How do I get the window dimension or size in Blazor WebAssembly?

Platform: Blazor| Category: JavaScript Interop

Window dimension values are read using JavaScript Interop with the window.innerHeight and window.innerWidth properties.
Follow these steps to get the window dimension value in Blazor WebAssembly.

[Index.razor]

@page "/"
@inject IJSRuntime JsRuntime

<h1>Window Dimensions</h1>

<button class="btn btn-primary" @onclick="OnButtonClick">Get Dimensions</button><br /><br />

<p>Window Height: @Height</p>
<p>Window Width: @Width</p>

@code {

    public int Height { get; set; }
    public int Width { get; set; }

    private async Task OnButtonClick()
    {
        var dimension = await JsRuntime.InvokeAsync<WindowDimension>("getWindowDimensions");
        Height = dimension.Height;
        Width = dimension.Width;
    }

    public class WindowDimension
    {
        public int Width { get; set; }
        public int Height { get; set; }
    }

}

[index.html]

<body> 
      . . . 
      . . . 
 
   <script> 
        window.getWindowDimensions = function () {
            return {
                width: window.innerWidth,
                height: window.innerHeight
            };
        }; 
    </script> 
</body >

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.