AutoFocus in ASP.Net RazorPages

The other day I was creating a couple of list pages in an ASP.Net Razor Pages application and I wanted to set the focus on a search input when the page loaded.  

Easy enough.  The bottom of my layout page already contains a section for adding page specific javascript.


@RenderSection("scripts", required: false)

My first attempt was to simply select the input element using the "focus()" function.

@section scripts{
   <script type="application/javascript">
      $(window).on("load", function(){
         document.getElementById("Filter").focus();
      });
   </script>
}

That worked but if the user had already entered a search term the cursor was placed at the beginning of the input box. What I really wanted was to place the cursor at the end of the text, allowing the user to refine the search.  I couldn't find a built in 'focusAtEnd' method. So, to accomplish setting the focus at end of then input I had actually select the text after the input using the following code.

$(window).on("load", function(){
    let el = document.getElementById("Filter");
    el.focus();
    el.setSelectionRange(el.value.length, el.value.length);
});

One of the fun and often annoying things about programming is that instead of saying what we want to do, "Focus on this input and place the cursors at the end of the current value" we have to come up with tricks like this where we focus on the input and then do a 'phantom' select to move the cursor where we want it to be.

Other Scenarios

Example code is rarely complete. So, here are some ways we could expand or improve on this topic.

  • Implement this as a tag helper
  • Create the tag helper as a shared Razor component or class library

Learn More

Notes

I initially went with this snippet from CSS-Tricks but when writing this post I discovered that the 'selectionStart' method is obsolete.

Cover image by Dmitry Ratushny on Unsplash