Search code examples
c#cssblazor.net-5blazor-webassembly

How to hide mouse cursor in Microsoft Blazor after being inactive for sometime without using JavaScript?


There is nothing much description here. All I want is to reduce JavaScript function call from Blazor to let the Blazor do what it is made for, "Avoid using JavaScript".


Solution

  • So, answering here just to help future seekers of a similar problem without using complex coding.

    Put the following code in the Index.razor file or any component of your choice where you want to hide the mouse cursor.

    private bool _showMouse;
    private static Timer _timer = new(_timerDuration);
    private static double _timerDuration = 5000; //In my case, I wanted to hide the cursor after five seconds.
    
    protected override async Task OnInitializedAsync()
    {
        _timer.Start();
    }
    
    protected override async Task OnAfterRenderAsync(bool firstRender) 
    {
        if (firstRender)
        {    
            _timer.Elapsed += (sender, args) =>
            {
                _showMouse = false;
                StateHasChanged();
            };
        }
    }
    
    private void OnMouseMove(MouseEventArgs e)
    {
          _showMouse = true;
          _timer.Interval = 5000;
    }
    

    Add this to the In-Line style of your root element within which you would like your mouse to be hidden after a specified time of inactivity.

    <div @onmousemove="OnMouseMove" style="cursor: @(_showMouse ? "unset" : "none");">
      ...
      .
      .
      ...
    </div>
    

    Thank you. I hope it might help someone in the future!