2

//How can I make the cursor blink? in this example i'm using a timer and in the debug mode I can //see the CursorCssClass changing but the the cursor does blink in the browser.

<section id="hero" class="d-flex flex-column justify-content-center align-items-center">
    <div class="hero-container">
        <h1>test test</h1>
        <p>I'm tester <span style="@CursorCssClass">|</span></p>
    </div>
</section>
@code {

    private bool hideCursor = true;
    private System.Timers.Timer aTimer;
    private string CursorCssClass => hideCursor ? "opacity: 0" : "opacity: 1";

    private void ToggleCursor()
    {
        aTimer = new System.Timers.Timer();
        aTimer.Interval = 1000;
        aTimer.Elapsed += OnTimedEvent;
        aTimer.AutoReset = true;
        aTimer.Enabled = true;
    }
    private void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        hideCursor = !hideCursor;
    }
    protected override Task OnInitializedAsync()
    {
      ToggleCursor();
        return base.OnInitializedAsync();
    }
}
  • `void` event handlers don't automatically update the UI. You'll have to run `StateHasChanged()` Also, I'm not experienced with the lambda style declarations-- do they only run on initialization of CursorCssClass, or is it a kind of setter? Also, OnInitializedAsync runs 2x if you're using prerender in server-hosted site-- that might lead to strange results in this case (I've had problems with creating timers in ANY page event). – Bennyboy1973 Sep 07 '21 at 02:45
  • Add a CSS isolation file (like Index.razor.css) and use CSS, like https://codepen.io/ArtemGordinsky/pen/GnLBq – Nicola Biada Sep 07 '21 at 05:05

1 Answers1

1

A Timer is an external (non-Blazor) event so you need to call (invoke) StateHasChanged:

private void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
    hideCursor = !hideCursor;
    InvokeAsync(StateHasChanged);
}

Furthermore, you need to Dispose the Timer.

H H
  • 263,252
  • 30
  • 330
  • 514